:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import re
import json
import base64
import logging
import binascii
from datetime import UTC, datetime, timedelta
from typing import Any, cast
from django.conf import settings
from django.db import models
from django.utils import timezone as django_timezone
import posthoganalytics
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field, extend_schema_serializer
from rest_framework import serializers
from rest_framework.request import Request
from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.fields import JSONTolerantListField, RepeatedOrCommaSeparatedListField
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.event_usage import groups
from posthog.integrations.fields import IntegrationReferenceField
from posthog.models.user_integration import UserIntegration
from posthog.oauth_provenance import get_oauth_client_id, is_interactive_desktop_grant
from posthog.object_tags.kinds import OBJECT_KINDS
from posthog.security.url_validation import is_url_allowed, resolve_url_hosts_ips
from posthog.temporal.oauth import POSTHOG_CODE_OAUTH_APP_CLIENT_IDS
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.agent_instructions import AGENT_INSTRUCTIONS_MAX_LENGTH
from products.tasks.backend.facade.api import CHANNEL_INSTRUCTIONS_MAX_BYTES, TASK_RUN_FAILURE_ERROR_TYPES
from products.tasks.backend.facade.client_provenance import is_api_key_request, is_sandbox_oauth_request
from products.tasks.backend.facade.contracts import (
ChannelContributorsDTO,
ChannelDTO,
ChannelFeedMessageDTO,
ChannelInstructionsDTO,
DesktopAccessReason,
SandboxCustomImageDTO,
SandboxEnvironmentDTO,
SlackThreadReferenceDTO,
SpaceFeatureRequest,
SpaceGoalRequest,
SpaceSetupRequest,
SpaceSetupStartedDTO,
TaskActivityDTO,
TaskActivityPageDTO,
TaskCreateResponseDTO,
TaskDetailDTO,
TaskMentionDTO,
TaskRunDetailDTO,
TaskRunResponseDTO,
TaskSummaryDTO,
TaskThreadMessageDTO,
TaskUserBasicInfo,
WizardCloudRunDTO,
)
from products.tasks.backend.facade.enums import TaskChannelWriteType
from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, ModelChoice, available_model_choices
from products.tasks.backend.facade.run_config import (
ALL_INITIAL_PERMISSION_MODE_CHOICES,
CODEX_INITIAL_PERMISSION_MODE_CHOICES,
CONTEXT_WINDOW_CHOICES,
INITIAL_PERMISSION_MODE_CHOICES,
REASONING_EFFORTS,
WARMABLE_ORIGIN_PRODUCTS,
LLMProvider,
PrAuthorshipMode,
ReasoningEffort,
RunSource,
RuntimeAdapter,
TaskArtifactAdapter,
TaskArtifactStatus,
TaskArtifactType,
get_model_access_error,
get_reasoning_effort_error,
get_runtime_adapter_for_model,
)
from products.tasks.backend.facade.task_defaults import CLOUD_TARGET_PATTERN
logger = logging.getLogger(__name__)
TASK_RUN_REASONING_EFFORT_CHOICES = [effort.value for effort in ReasoningEffort]
PI_TASK_INCOMPATIBLE_RUN_FIELDS = ("runtime_adapter", "context_window", "fast_mode", "initial_permission_mode")
def _pi_task_run_request_errors(attrs: dict[str, Any]) -> dict[str, str]:
errors: dict[str, str] = {}
if attrs.get("claude_model_access") == "own-subscription":
errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."
if attrs.get("codex_model_access") == "own-subscription":
errors["codex_model_access"] = "Pi tasks cannot use a ChatGPT plan."
for field in PI_TASK_INCOMPATIBLE_RUN_FIELDS:
if attrs.get(field) is not None:
errors[field] = "This field cannot be used with a Pi task."
return errors
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,
team.id,
user_id,
for_control=True,
)
return task_runtime == tasks_facade.TaskRuntime.PI
def _is_desktop_app_grant(request: Request) -> bool:
return get_oauth_client_id(request) in POSTHOG_CODE_OAUTH_APP_CLIENT_IDS and is_interactive_desktop_grant(request)
def _may_select_claude_plan(request: Request) -> bool:
"""Whether this caller may bill a run to a Claude plan.
PostHog stores no Claude token: a subscription run asks the person who started it for
one over the run's stream, and fails if nobody answers. The caller therefore has to be
something that can answer, on behalf of someone whose plan can be billed. Desktop does
it interactively; an API key acting as a user is a deliberate server-to-server
credential whose owner can run the same relay unattended, which is what internal
automation uses.
Sandbox tokens are excluded by both checks — the agent's own code must never be able to
put a run on its owner's plan.
"""
return _is_desktop_app_grant(request) or is_api_key_request(getattr(request, "successful_authenticator", None))
def _validate_subscription_caller(attrs: dict[str, Any], context: dict[str, Any]) -> None:
request = context.get("request")
if request is None:
return
access = attrs.get("claude_model_access")
if access is None and (run_id := attrs.get("resume_from_run_id")):
view = context.get("view")
kwargs = getattr(view, "kwargs", {})
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:
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 not _may_select_claude_plan(request):
raise serializers.ValidationError(
{
"claude_model_access": (
"Only PostHog Desktop or an API key can start a run on your Claude plan. "
"Start the task from Desktop, authenticate with an API key, or select "
"'posthog-gateway' to use PostHog credits."
)
}
)
# The PostHog API serves the ChatGPT token, so any caller can resume a Codex plan run.
if attrs.get("codex_model_access") == "own-subscription" and is_sandbox_oauth_request(request):
raise serializers.ValidationError({"codex_model_access": "Only a user can select a ChatGPT plan."})
def request_distinct_id(context: dict[str, Any]) -> str | None:
"""The acting user's distinct id, for flag evaluation. `None` when there isn't one."""
user = getattr(context.get("request"), "user", None)
if user is None or not user.is_authenticated or not user.distinct_id:
return None
return str(user.distinct_id)
def _capture_rejected_reasoning_effort(
context: dict[str, Any],
*,
runtime_adapter: str | None,
model: str | None,
reasoning_effort: str | None,
error: str,
) -> None:
"""Record a rejected runtime_adapter/model/reasoning_effort combination server-side.
This validation only ever reached the caller as a 400 response body, so recurring
misconfigurations (e.g. a model missing from the supported-effort map) were invisible
beyond individual client-side error toasts.
"""
team = context.get("team")
logger.warning(
"Rejected task run reasoning_effort/model combination",
extra={
"team_id": getattr(team, "id", None),
"runtime_adapter": runtime_adapter,
"model": model,
"reasoning_effort": reasoning_effort,
},
)
request = context.get("request")
user = getattr(request, "user", None)
if user is None or not user.is_authenticated or not user.distinct_id:
return
posthoganalytics.capture(
distinct_id=str(user.distinct_id),
event="task run reasoning effort rejected",
properties={
"runtime_adapter": runtime_adapter,
"model": model,
"reasoning_effort": reasoning_effort,
"error": error,
},
groups=groups(team=team),
)
class TaskUserBasicInfoSerializer(DataclassSerializer):
"""Response shape for a `created_by` user — mirrors core `UserBasicSerializer` output."""
class Meta:
dataclass = TaskUserBasicInfo
class SlackThreadReferenceSerializer(DataclassSerializer):
class Meta:
dataclass = SlackThreadReferenceDTO
TASK_RUN_ARTIFACT_MAX_SIZE_BYTES = 30 * 1024 * 1024
TASK_RUN_PDF_ARTIFACT_MAX_SIZE_BYTES = 10 * 1024 * 1024
# Inline uploads carry their content in the JSON body, which Django bounds with
# DATA_UPLOAD_MAX_MEMORY_SIZE before any serializer runs. Base64 inflates content by four
# thirds, so only three quarters of that ceiling is reachable, less room for the surrounding
# JSON. Larger artifacts go through prepare_upload, which presigns straight to object storage.
TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES = (settings.DATA_UPLOAD_MAX_MEMORY_SIZE * 3) // 4 - 1024 * 1024
# The labels repeat the values because the published OpenAPI enum lists these exact pairs.
class TaskRunArtifactType(models.TextChoices):
PLAN = "plan", "plan"
CONTEXT = "context", "context"
REFERENCE = "reference", "reference"
OUTPUT = "output", "output"
ARTIFACT = "artifact", "artifact"
TREE_SNAPSHOT = "tree_snapshot", "tree_snapshot"
USER_ATTACHMENT = "user_attachment", "user_attachment"
SKILL_BUNDLE = "skill_bundle", "skill_bundle"
TASK_RUN_ARTIFACT_CONTENT_ENCODING_CHOICES = ["utf-8", "base64"]
TASK_RUN_SKILL_BUNDLE_FORMAT_CHOICES = ["zip"]
TASK_RUN_SKILL_SOURCE_CHOICES = ["user", "repo", "marketplace", "codex"]
POSTHOG_OBJECT_KIND_CHOICES = list(OBJECT_KINDS)
TASK_RUN_LIVING_ARTIFACT_TYPE_CHOICES = [choice for choice, _label in TaskArtifactType.choices]
TASK_RUN_LIVING_ARTIFACT_ADAPTER_CHOICES = [choice for choice, _label in TaskArtifactAdapter.choices]
TASK_RUN_LIVING_ARTIFACT_WRITE_ADAPTER_CHOICES = TASK_RUN_LIVING_ARTIFACT_ADAPTER_CHOICES
def get_task_run_artifact_max_size_bytes(
artifact_name: str | None,
content_type: str | None,
artifact_type: str | None = None,
) -> int:
if artifact_type != "user_attachment":
return TASK_RUN_ARTIFACT_MAX_SIZE_BYTES
normalized_name = (artifact_name or "").lower()
normalized_content_type = (content_type or "").split(";")[0].strip().lower()
if normalized_name.endswith(".pdf") or normalized_content_type == "application/pdf":
return TASK_RUN_PDF_ARTIFACT_MAX_SIZE_BYTES
return TASK_RUN_ARTIFACT_MAX_SIZE_BYTES
def get_task_run_artifact_inline_max_size_bytes(
artifact_name: str | None,
content_type: str | None,
artifact_type: str | None = None,
) -> int:
return min(
get_task_run_artifact_max_size_bytes(artifact_name, content_type, artifact_type),
TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES,
)
def build_task_run_artifact_size_error(
artifact_name: str | None,
max_size_bytes: int,
) -> str:
max_mb = max_size_bytes // (1024 * 1024)
if (artifact_name or "").lower().endswith(".pdf"):
return f"{artifact_name or 'Artifact'} exceeds the {max_mb}MB attachment limit for PDFs in cloud runs"
return f"{artifact_name or 'Artifact'} exceeds the {max_mb}MB attachment limit"
class AgentDefinitionSerializer(serializers.Serializer):
"""Serializer for agent definitions"""
id = serializers.CharField()
name = serializers.CharField()
agent_type = serializers.CharField()
description = serializers.CharField()
config = serializers.DictField(default=dict)
is_active = serializers.BooleanField(default=True)
class TaskRunUpdateSerializer(serializers.Serializer):
status = serializers.ChoiceField(
choices=["not_started", "queued", "in_progress", "completed", "failed", "cancelled"],
required=False,
help_text="Current execution status",
)
branch = serializers.CharField(
required=False, allow_null=True, help_text="Git branch name to associate with the task"
)
stage = serializers.CharField(
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.DictField(required=False, help_text="State of the run")
state_remove_keys = serializers.ListField(
child=serializers.CharField(),
required=False,
allow_empty=False,
help_text="State keys to remove atomically before applying any state updates.",
)
state_append = serializers.DictField(
required=False,
allow_empty=False,
help_text=(
"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."
),
)
error_message = serializers.CharField(
required=False, allow_null=True, allow_blank=True, help_text="Error message if execution failed"
)
error_type = serializers.ChoiceField(
choices=TASK_RUN_FAILURE_ERROR_TYPES,
required=False,
allow_null=True,
help_text="Why the run failed, set by the caller that marked it failed.",
)
class TaskRunSkillBundleMetadataSerializer(serializers.Serializer):
skill_name = serializers.CharField(
allow_blank=False,
max_length=255,
help_text="Name of the local skill included in a skill_bundle artifact.",
)
skill_source = serializers.ChoiceField(
choices=TASK_RUN_SKILL_SOURCE_CHOICES,
help_text="Local source for the uploaded skill bundle, such as user or repo.",
)
content_sha256 = serializers.RegexField(
regex=r"^[a-f0-9]{64}$",
help_text="SHA-256 hex digest of the uploaded skill bundle bytes.",
)
bundle_format = serializers.ChoiceField(
choices=TASK_RUN_SKILL_BUNDLE_FORMAT_CHOICES,
help_text="Archive format used for the local skill bundle.",
)
schema_version = serializers.IntegerField(
min_value=1,
help_text="Version of the local skill bundle metadata schema.",
)
class TaskRunPostHogReferenceMetadataSerializer(serializers.Serializer):
reference_type = serializers.ChoiceField(
choices=["posthog_object"],
help_text="Reference metadata type. posthog_object identifies a live PostHog object.",
)
object_kind = serializers.ChoiceField(
choices=POSTHOG_OBJECT_KIND_CHOICES,
help_text="PostHog object kind used to resolve the reference.",
)
object_id = serializers.CharField(
max_length=16384,
help_text="Exact PostHog object identifier, flag key, event name, or SQL query.",
)
source_message_ids = serializers.ListField(
child=serializers.CharField(max_length=255),
max_length=100,
help_text="Completed assistant message identifiers that referenced the object.",
)
occurrence_count = serializers.IntegerField(
min_value=1,
help_text="Number of distinct completed assistant messages that referenced the object.",
)
@extend_schema_field(
PolymorphicProxySerializer(
component_name="TaskRunArtifactMetadata",
serializers=[TaskRunSkillBundleMetadataSerializer, TaskRunPostHogReferenceMetadataSerializer],
resource_type_field_name=None,
)
)
class TaskRunArtifactMetadataField(serializers.JSONField):
pass
def get_initial_permission_mode_error(initial_permission_mode: str | None, runtime_adapter: str | None) -> str | None:
"""Error message when a permission mode does not belong to the selected runtime, else ``None``.
The field's own ``ChoiceField`` accepts the union of both runtimes' vocabularies, which share only
``plan`` and ``auto``. Pairing is checked here so every entry point that takes a mode — run, warm,
and task create — agrees on which pairs are valid, rather than a warm booting a sandbox on a mode
the matching run request would reject.
"""
if initial_permission_mode is None:
return None
# With no runtime pinned the mode rides along and is clamped to whichever runtime the
# stored defaults resolve to at run creation — requiring the adapter here would force
# composers to pin the model just to state a mode, blocking server-side default resolution.
if runtime_adapter is None:
return None
allowed_permission_modes = (
list(CODEX_INITIAL_PERMISSION_MODE_CHOICES)
if runtime_adapter == RuntimeAdapter.CODEX.value
else list(INITIAL_PERMISSION_MODE_CHOICES)
)
if initial_permission_mode in allowed_permission_modes:
return None
allowed_values = ", ".join(f"'{value}'" for value in allowed_permission_modes)
return (
f"Invalid choice '{initial_permission_mode}' for runtime_adapter "
f"'{runtime_adapter}'. Supported values: {allowed_values}."
)
def validate_task_run_artifact_metadata(attrs: dict[str, Any]) -> dict[str, Any]:
artifact_type = attrs.get("type")
metadata = attrs.get("metadata")
if artifact_type != "skill_bundle":
return attrs
if not metadata:
raise serializers.ValidationError({"metadata": "Skill bundle artifacts require metadata"})
return attrs
class TaskRunArtifactResponseSerializer(serializers.Serializer):
id = serializers.CharField(required=False, help_text="Stable identifier for the artifact within this run")
name = serializers.CharField(help_text="Artifact file name")
type = serializers.CharField(help_text="Artifact classification (plan, context, etc.)")
source = serializers.CharField( # type: ignore[assignment]
required=False,
allow_blank=True,
help_text="Source of the artifact, such as agent_output or user_attachment",
)
size = serializers.IntegerField(required=False, help_text="Artifact size in bytes")
content_type = serializers.CharField(required=False, allow_blank=True, help_text="Optional MIME type")
metadata = TaskRunArtifactMetadataField(
required=False,
help_text="Structured metadata for a skill bundle or a PostHog object reference.",
)
storage_path = serializers.CharField(
required=False,
help_text="S3 object key for file artifacts. Reference artifacts do not have one.",
)
uploaded_at = serializers.CharField(help_text="Timestamp when the artifact was uploaded or registered")
uploaded_by = serializers.ChoiceField(
choices=["agent", "user"],
required=False,
help_text="Whether the artifact version was uploaded by the task agent or an interactive user.",
)
uploaded_by_user_id = serializers.IntegerField(
required=False,
help_text="User id for an interactive user upload. Absent for agent uploads and legacy entries.",
)
dismissed_at = serializers.CharField(
required=False,
help_text="Timestamp when a user dismissed the artifact. Absent while the artifact is shown.",
)
url = serializers.URLField(
required=False,
help_text=(
"Stable download URL for the artifact. Populated on the finalize-upload response so "
"the caller can link to the file; it redirects to a fresh presigned URL on each request "
"and is not persisted on the manifest."
),
)
class TaskRunDetailSerializer(DataclassSerializer):
"""Detail response for a task run.
Reads from a frozen ``TaskRunDetailDTO`` produced by the facade mapper (which computes the
presigned ``log_url`` and parses ``runtime_adapter`` / ``provider`` / ``model`` /
``reasoning_effort`` off the run state). ``task`` is the parent task id. Reused as the nested
``latest_run`` shape by the task detail response.
"""
task = serializers.UUIDField(help_text="Parent task id this run belongs to.")
scheduled_at = serializers.DateTimeField(
required=False,
allow_null=True,
default_timezone=UTC,
help_text="Earliest start time in UTC. Null for runs without a schedule.",
)
log_url = serializers.URLField(
allow_null=True, required=False, help_text="Presigned S3 URL for log access (valid for 1 hour)."
)
artifacts = TaskRunArtifactResponseSerializer(many=True, read_only=True)
runtime_adapter = serializers.ChoiceField(
choices=RuntimeAdapter.choices,
allow_null=True,
required=False,
help_text="Configured runtime adapter for this run, such as 'claude' or 'codex'.",
)
provider = serializers.ChoiceField(
choices=[provider.value for provider in LLMProvider],
allow_null=True,
required=False,
help_text="Configured LLM provider for this run, such as 'anthropic' or 'openai'.",
)
model = serializers.CharField(
allow_null=True, required=False, help_text="Configured LLM model identifier for this run."
)
reasoning_effort = serializers.ChoiceField(
choices=TASK_RUN_REASONING_EFFORT_CHOICES,
allow_null=True,
required=False,
help_text="Configured reasoning effort for this run when the selected model supports it.",
)
preview_available = serializers.BooleanField(
required=False,
help_text=(
"True when this run's sandbox serves a dev stack preview, so clients can offer the "
"preview link. Open it through the run's `preview/` endpoint, which mints a fresh "
"access token on every request."
),
)
task_summary = serializers.CharField(
allow_null=True,
help_text="Latest summary for this task, including a summary inherited from an earlier run.",
)
task_tags = serializers.ListField(
child=serializers.CharField(),
help_text="Latest slug tags for this task, including tags inherited from an earlier run.",
)
class Meta:
dataclass = TaskRunDetailDTO
fields = [
"id",
"task",
"stage",
"branch",
"status",
"environment",
"runtime_adapter",
"provider",
"model",
"reasoning_effort",
"log_url",
"error_message",
"output",
"task_summary",
"task_tags",
"state",
"artifacts",
"created_at",
"updated_at",
"completed_at",
"scheduled_at",
"preview_available",
]
class WizardCloudRunSerializer(DataclassSerializer):
"""The team's active onboarding wizard cloud run, used to rehydrate
the setup-progress FAB when the run was started server-side (drop flow)."""
task_id = serializers.UUIDField(help_text="Id of the onboarding wizard task.")
run_id = serializers.UUIDField(help_text="Id of the task's latest run, for reconnecting to its progress stream.")
status = serializers.CharField(help_text="Latest run status (e.g. queued, in_progress, completed, failed).")
started_at = serializers.DateTimeField(
allow_null=True, required=False, help_text="When the run was created, for the FAB's elapsed timer."
)
class Meta:
dataclass = WizardCloudRunDTO
fields = ["task_id", "run_id", "status", "started_at"]
# The relationship a client asserts between a task and a signal report when creating a task from the
# report (e.g. PostHog Desktop inbox), recorded as a signals `task_run` work-log entry. This is a
# free-form label — the same as the `task_run` artefact `(product, type)` values, which have never
# been access-controlled — so no relationship is reserved here either. `implementation` additionally
# opens the auto-start spend gate (recorded server-side via `record_report_task`). Only the routing-
# safe format is enforced, so a malformed value returns 400 rather than 500 from the artefact schema.
# Mirrors the routing-safe identifier rule in `signals` `artefact_schemas` (_IDENTIFIER_PART_RE),
# kept inline so presentation never imports the other product's internals.
_SIGNAL_REPORT_TASK_RELATIONSHIP_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
# String literals rather than an import: presentation must not import signals internals, and the
# vocabulary (products/signals/backend/artefact_schemas.py TASK_RUN_TYPE_*) is stable.
_SERVER_ONLY_SIGNAL_REPORT_TASK_RELATIONSHIPS = frozenset({"research", "repo_selection", "scout"})
class TaskSerializer(DataclassSerializer):
"""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``.
"""
latest_run = TaskRunDetailSerializer(allow_null=True, required=False, help_text="Latest run details for this task")
created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
slack_thread_references = SlackThreadReferenceSerializer(many=True, read_only=True)
# Not `read_only`, even though this is a response-only serializer: `@validated_request` re-reads
# its own output through `to_internal_value`, which drops read-only fields, and `runtime` is
# required on `TaskDetailDTO` — so a read-only declaration makes that round-trip raise. Writes
# never reach here; they go through `TaskCreateSerializer` / `TaskWriteSerializer`.
runtime = serializers.ChoiceField(
choices=tasks_facade.TaskRuntime.choices,
help_text="Agent protocol and harness used for this task's runs.",
)
origin_key = serializers.CharField(
allow_null=True,
required=False,
help_text=(
"Stable key of the server-side flow that created this task, e.g. "
"`desktop_onboarding_session:<user_id>`. Null for tasks people create themselves."
),
)
client_provenance = serializers.ChoiceField(
choices=tasks_facade.TaskClientProvenance.choices,
allow_null=True,
required=False,
help_text="First-party PostHog client that created this task.",
)
class Meta:
dataclass = TaskDetailDTO
fields = [
"id",
"task_number",
"slug",
"title",
"title_manually_set",
"description",
"origin_product",
"runtime",
"repository",
"repositories",
"github_integration",
"github_user_integration",
"signal_report",
"json_schema",
"internal",
"archived",
"archived_at",
"latest_run",
"created_at",
"updated_at",
"last_activity_at",
"created_by",
"ci_prompt",
"channel",
"slack_thread_references",
"origin_key",
"client_provenance",
]
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):
"""The task ``run`` action's response: the refreshed task detail plus the run this call made.
``run`` is the run the call created or activated — the payload a caller reads run-scoped ids
from, instead of inferring them from ``latest_run`` (or, worse, the top-level task ``id``).
"""
run_error = serializers.CharField(required=False, help_text="Error returned when the run could not start.")
run = TaskRunDetailSerializer(
allow_null=True,
required=False,
help_text=(
"The run this call created or activated. Read run-scoped ids from here — `run.id` is "
"the id the run's stream and command endpoints take, while the top-level `id` is the "
"task's. Set on every 200; when `run_error` is also set, the run exists but its "
"workflow did not start."
),
)
class Meta(TaskCreateResponseSerializer.Meta):
dataclass = TaskRunResponseDTO
fields = [*TaskCreateResponseSerializer.Meta.fields, "run"]
TASK_DESCRIPTION_PREVIEW_LENGTH = 1000
TASK_DESCRIPTION_PREVIEW_HELP_TEXT = (
f"First {TASK_DESCRIPTION_PREVIEW_LENGTH} characters of the description, so a summary "
"surface can show a prompt snippet without the full body. Open the task for the complete text."
)
@extend_schema_serializer(component_name="TaskBasic")
class TaskBasicSerializer(TaskSerializer):
"""Basic list response for a task, returned when the list is asked for ``basic=true``.
A surface that renders only a summary of each task asks for the basic payload and gets this
smaller shape. It drops the full ``description`` body, which dominates the list payload, and
replaces it with ``description_preview`` (the first characters) so a feed can still show a
prompt snippet. The default list response keeps the full ``description``, and ``retrieve``
always returns it. A client uses the ``search`` query parameter to match description text
server-side.
"""
description_preview = serializers.SerializerMethodField(
help_text=TASK_DESCRIPTION_PREVIEW_HELP_TEXT,
)
class Meta(TaskSerializer.Meta):
fields = [field for field in TaskSerializer.Meta.fields if field != "description"] + ["description_preview"]
@extend_schema_field(serializers.CharField(help_text=TASK_DESCRIPTION_PREVIEW_HELP_TEXT))
def get_description_preview(self, obj: TaskDetailDTO) -> str:
return (obj.description or "")[:TASK_DESCRIPTION_PREVIEW_LENGTH]
TaskListItemSerializer = PolymorphicProxySerializer(
component_name="TaskListItem",
serializers=[TaskSerializer, TaskBasicSerializer],
resource_type_field_name=None,
)
class TaskWriteSerializer(serializers.Serializer):
title = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
help_text="Short human-readable title. Auto-generated from `description` when omitted.",
)
title_manually_set = serializers.BooleanField(
required=False,
help_text="Whether the title was set by a human (vs auto-generated from the description).",
)
description = serializers.CharField(
required=False,
allow_blank=True,
help_text="Free-form description of the work to be done. Used as the prompt passed to the agent.",
)
origin_product = serializers.ChoiceField(
choices=tasks_facade.TaskOriginProduct.choices,
required=False,
help_text=(
"PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). "
"Origins reserved for server-created agents cannot be set through this API."
),
)
repository = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
allow_null=True,
help_text="Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).",
)
repositories = serializers.ListField(
child=serializers.CharField(max_length=255),
required=False,
max_length=10,
help_text="GitHub repositories available to this task, each in `organization/repo` format.",
)
github_integration = IntegrationReferenceField(
kinds=["github"],
required=False,
allow_null=True,
help_text="GitHub integration for this task.",
)
# UserIntegration is scoped to request.user in validate_github_user_integration.
github_user_integration = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
queryset=UserIntegration.objects.filter(kind="github"),
required=False,
allow_null=True,
help_text="User-scoped GitHub integration to use for user-authored cloud runs.",
)
# Mirrors the ModelSerializer-generated FK field: queryset is the full report manager
# (team scope is enforced by validate_signal_report below). Bound lazily in __init__ so
# importing this module never touches the signals model.
signal_report = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
queryset=UserIntegration.objects.none(), # placeholder, replaced in __init__
required=False,
allow_null=True,
help_text="Signal report this task implements, when created from a report.",
)
# Write-only: recorded as the signals `task_run` artefact type when linking a task to a report.
signal_report_task_relationship = serializers.CharField(
required=False,
write_only=True,
max_length=200,
help_text=(
"How the created task relates to the signal report (e.g. 'implementation', 'discussion'). "
"Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start "
"spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted "
"except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). "
"Non-implementation labels count toward the report's discussion task limit."
),
)
json_schema = serializers.JSONField(
required=False,
allow_null=True,
help_text="JSON schema used to validate the output of the task.",
)
# `internal` is deliberately not writable here: only server-side creators (auto-start,
# research, loops) set it via the facade, and it decides whether the task is listed.
archived = serializers.BooleanField(
required=False,
help_text="If true, the task is hidden from default list responses.",
)
ci_prompt = serializers.CharField(
required=False,
allow_null=True,
allow_blank=True,
help_text="Custom prompt for CI fixes. If blank, a default prompt will be used.",
)
branch = serializers.CharField(
max_length=255,
required=False,
allow_null=True,
allow_blank=True,
write_only=True,
help_text=(
"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
# null when nothing is selected, so they take allow_null=True (null == "no
# selection", same as omitting the key — it's read back as None downstream).
# null and "" are not interchangeable: model keeps allow_blank=False so an
# empty string, which is never a valid model id, is still rejected.
runtime_adapter = serializers.ChoiceField(
choices=RuntimeAdapter.choices,
required=False,
default=None,
allow_null=True,
write_only=True,
help_text=(
"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(
required=False,
default=None,
allow_blank=False,
allow_null=True,
write_only=True,
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=list(REASONING_EFFORTS),
required=False,
default=None,
allow_null=True,
write_only=True,
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,
required=False,
default=None,
allow_null=True,
write_only=True,
help_text=(
"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(
required=False,
default=None,
allow_null=True,
allow_blank=True,
write_only=True,
help_text=(
"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(
required=False,
default=list,
child=serializers.CharField(max_length=128),
write_only=True,
help_text=(
"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 = serializers.BooleanField(
required=False,
allow_null=True,
default=None,
write_only=True,
help_text=(
"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
queryset=UserIntegration.objects.none(), # placeholder, replaced in __init__
required=False,
allow_null=True,
help_text="Channel this task is owned by (the channel it was kicked off in).",
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# SignalReport is scoped to the request team by the field; bind its queryset lazily so
# importing this module never touches the signals model at import time.
signal_report_field = cast(serializers.PrimaryKeyRelatedField, self.fields["signal_report"])
signal_report_field.queryset = tasks_facade.signal_report_queryset() # type: ignore[arg-type] # DRF stubs type queryset as a Manager, which django-stubs treats as a descriptor
channel_field = cast(serializers.PrimaryKeyRelatedField, self.fields["channel"])
channel_field.queryset = tasks_facade.channel_queryset() # type: ignore[arg-type] # DRF stubs type queryset as a Manager, which django-stubs treats as a descriptor
def validate_channel(self, value):
request = self.context.get("request")
user = getattr(request, "user", None)
user_id = getattr(user, "id", None)
if value is None:
return value
if value.deleted or value.channel_type not in {"public", "personal", "private"}:
raise serializers.ValidationError("Space not found")
if value.channel_type == "personal" and value.created_by_id != user_id:
raise serializers.ValidationError("Private spaces can only be used by their owner")
if value.channel_type == "private" and not tasks_facade.channel_exists(
self.context["team"].id, value.id, user_id
):
raise serializers.ValidationError("Space not found")
return value
def validate_github_user_integration(self, value):
"""Validate that the GitHub user integration belongs to the authenticated user."""
request = self.context.get("request")
user = getattr(request, "user", None)
if value and value.user_id != getattr(user, "id", None):
raise serializers.ValidationError("User integration must belong to the authenticated user")
return value
def validate_origin_product(self, value):
"""Reject internal-only origins that are set by server-side flows, never by API callers."""
if value in tasks_facade.TASK_SERVER_ONLY_ORIGIN_PRODUCTS:
raise serializers.ValidationError(f"origin_product '{value}' is reserved for server-created tasks")
return value
def validate_repository(self, value):
"""Validate repository configuration"""
if not value:
return value
parts = value.split("/")
if len(parts) != 2 or not parts[0] or not parts[1]:
raise serializers.ValidationError("Repository must be in the format organization/repository")
return value.lower()
def validate_repositories(self, value: list[str]) -> list[str]:
repositories = [self.validate_repository(repository) for repository in value]
if len(set(repositories)) != len(repositories):
raise serializers.ValidationError("Repositories must be unique")
return repositories
def validate_signal_report(self, value):
if value and value.team_id != self.context["team"].id:
raise serializers.ValidationError("Signal report must belong to the same team")
return value
def validate_signal_report_task_relationship(self, value: str) -> str:
normalized = value.strip()
if not _SIGNAL_REPORT_TASK_RELATIONSHIP_RE.fullmatch(normalized):
raise serializers.ValidationError(
"Must contain only lowercase letters, numbers, underscores, or hyphens, "
"and start with a lowercase letter or number."
)
# Labels the signals pipeline writes itself. Client-asserted, they would misrepresent a
# user-started task as pipeline work — and dodge the per-report cap, which counts every
# non-implementation label as a discussion except these server-only ones.
if normalized in _SERVER_ONLY_SIGNAL_REPORT_TASK_RELATIONSHIPS:
raise serializers.ValidationError(f"Relationship '{normalized}' is reserved for server-created tasks.")
return normalized
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
if "repository" in attrs and "repositories" in attrs:
legacy = attrs["repository"] or None
repositories = attrs["repositories"]
if legacy != (repositories[0] if repositories else None):
raise serializers.ValidationError({"repositories": "Conflicts with repository"})
repositories = attrs.get("repositories")
plural_repositories = repositories
if repositories is None and "repository" in attrs:
repositories = [attrs["repository"]] if attrs["repository"] else []
if plural_repositories and attrs.get("github_integration") is None:
instance_integration = getattr(self.instance, "github_integration", None)
if instance_integration is None:
raise serializers.ValidationError({"github_integration": "Required when repositories are configured"})
integration = attrs.get("github_integration") or getattr(self.instance, "github_integration", None)
if repositories and integration:
inaccessible = tasks_facade.inaccessible_repositories_via_integration(
self.context["team"].id, integration.id, repositories
)
if inaccessible:
raise serializers.ValidationError(
{"repositories": f"Not accessible via the selected GitHub integration: {', '.join(inaccessible)}"}
)
if "runtime" in self.initial_data and "runtime" not in self.fields:
raise serializers.ValidationError({"runtime": "Runtime cannot be changed after task creation."})
# Write-only and never persisted, but it selects which warm Run gets activated, so a
# gated model here still runs one. Reject rather than silently cold-creating instead.
model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))
if model_access_error is not None:
raise serializers.ValidationError({"model": model_access_error})
# Same reason: this selects the warm Run to activate, so it takes the pairing rule the run
# request applies rather than accepting a pair no runtime can serve.
permission_mode_error = get_initial_permission_mode_error(
attrs.get("initial_permission_mode"), attrs.get("runtime_adapter")
)
if permission_mode_error is not None:
raise serializers.ValidationError({"initial_permission_mode": permission_mode_error})
rel = attrs.get("signal_report_task_relationship")
if rel is not None:
if not attrs.get("signal_report"):
raise serializers.ValidationError(
{"signal_report_task_relationship": "Requires signal_report when set."}
)
if attrs.get("origin_product") != tasks_facade.TaskOriginProduct.SIGNAL_REPORT:
raise serializers.ValidationError(
{"signal_report_task_relationship": ("Requires origin_product signal_report when set.")}
)
if (
attrs.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT
and attrs.get("github_user_integration") is not None
):
raise serializers.ValidationError(
{"github_user_integration": "Signal report tasks use the team GitHub integration."}
)
# Repo is server-resolved for these code-access-exempt tasks; a client-set repo bypasses the gate.
if attrs.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT and (
attrs.get("repository") or attrs.get("repositories")
):
raise serializers.ValidationError(
{"repository": "Signal report tasks resolve their repository server-side."}
)
return attrs
@extend_schema_field(OpenApiTypes.STR)
class TaskRunScheduledAtField(serializers.DateTimeField):
pass
class TaskRunScheduleSerializer(serializers.Serializer):
scheduled_at = TaskRunScheduledAtField(
required=False,
allow_null=True,
default_timezone=UTC,
help_text=(
"Earliest start time for a one-off cloud run, in ISO 8601 format. "
"Must be in the future and within 30 days. Times without an offset use UTC. "
"Omit or send null to start immediately."
),
)
def validate_scheduled_at(self, value: datetime | None) -> datetime | None:
if value is not None:
now = django_timezone.now()
if value <= now or value > now + timedelta(days=30):
raise serializers.ValidationError("Choose a future time within 30 days.")
return value
class TaskCreateSerializer(TaskWriteSerializer, TaskRunScheduleSerializer):
start_run = serializers.BooleanField(
required=False,
default=False,
write_only=True,
help_text="Create the first cloud run. It starts immediately unless scheduled_at is set.",
)
signal_report_discussion_question = serializers.CharField(
required=False,
allow_blank=True,
write_only=True,
max_length=4_000,
help_text=(
"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."
),
)
naming_source = serializers.CharField(
required=False,
allow_blank=True,
write_only=True,
help_text=(
"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."
),
)
sandbox_environment_id = serializers.UUIDField(
required=False,
default=None,
allow_null=True,
write_only=True,
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 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,
required=False,
help_text="Agent protocol and harness used for this task's runs. Defaults to ACP when omitted.",
)
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
attrs = super().validate(attrs)
if attrs.get("scheduled_at") is not None and not attrs.get("start_run"):
raise serializers.ValidationError({"scheduled_at": "Set start_run to true to schedule a run."})
# Mirror image of the signal_report_task_relationship check: a report-less signal_report
# task still mints under the Signals OAuth app with the interactive run scope, but skips
# the per-report cap entirely. Require the report so the cap and interactive budget always
# see the run. Create-only, since origin_product is not writable on update.
if attrs.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT and not attrs.get(
"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",
"scheduled_at",
)
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, "runtime_adapter")
if key in run_serializer.validated_data
}
return attrs
class TaskRunSetOutputRequestSerializer(serializers.Serializer):
output = serializers.JSONField(
help_text="Output data from the run. Validated against the task's json_schema if one is set."
)
class TaskRunSetSummaryRequestSerializer(serializers.Serializer):
summary = serializers.CharField(
max_length=tasks_facade.TASK_RUN_SUMMARY_MAX_CHARS,
allow_blank=False,
trim_whitespace=True,
help_text="Complete running summary that replaces the prior summary.",
)
tags = serializers.ListField(
child=serializers.RegexField(
# Python's `$` also matches before a final newline; `(?!\n)` rejects it, as JavaScript does.
regex=r"^[a-z0-9]+(?:-[a-z0-9]+)*$(?!\n)",
max_length=tasks_facade.TASK_RUN_TAG_MAX_CHARS,
trim_whitespace=False,
help_text="A lowercase kebab-case slug, for example `feature-flags` or `bug-fix`.",
),
required=False,
max_length=tasks_facade.TASK_RUN_TAGS_MAX_COUNT,
help_text=(
"Complete set of slug tags that replaces the prior tags. The agent chooses the tags. "
"Omit the field to keep the current tags. Send an empty list to remove them."
),
)
class DesktopAccessResponseSerializer(serializers.Serializer):
allowed = serializers.BooleanField(help_text="Whether the selected project can use PostHog Desktop.")
reason = serializers.ChoiceField(
choices=DesktopAccessReason.choices,
allow_null=True,
help_text="Why Desktop access is blocked, or null when access is allowed.",
)
class LegacyDesktopAccessResponseSerializer(serializers.Serializer):
has_access = serializers.BooleanField(help_text="Whether the current project can use PostHog Desktop.")
has_loops_access = serializers.BooleanField(help_text="Whether the independent Loops feature is enabled.")
class TaskRunErrorResponseSerializer(serializers.Serializer):
detail = serializers.CharField(required=False, help_text="Human-readable validation error")
error = serializers.CharField(required=False, help_text="Human-readable error message")
type = serializers.CharField(required=False, help_text="Machine-readable error type")
code = serializers.CharField(required=False, help_text="Machine-readable error code")
retry_token = serializers.CharField(
required=False,
help_text="After confirmed warm startup nondelivery, echo this token in X-PostHog-Warm-Retry to retry the same run and message within 60 seconds.",
)
reason = serializers.ChoiceField(
choices=DesktopAccessReason.choices,
required=False,
help_text="Why PostHog Desktop access was denied, when applicable.",
)
attr = serializers.CharField(required=False, help_text="Request field associated with the error")
missing_artifact_ids = serializers.ListField(
child=serializers.CharField(),
required=False,
help_text="Artifact ids that could not be resolved for the run",
)
limit_type = serializers.ChoiceField(
choices=[("burst", "burst"), ("sustained", "sustained")],
required=False,
help_text="Which usage limit was hit on a rate_limited error: 'burst' (daily) or 'sustained' (monthly)",
)
reset_at = serializers.CharField(
required=False,
help_text="ISO 8601 timestamp when the hit usage limit resets, when known",
)
is_pro = serializers.BooleanField(
required=False,
help_text="Whether the team is on a Pro plan (drives the upgrade-prompt copy)",
)
class AgentListResponseSerializer(serializers.Serializer):
results = AgentDefinitionSerializer(many=True, help_text="Array of available agent definitions")
class TaskRunAppendLogRequestSerializer(serializers.Serializer):
entries = serializers.ListField(
child=serializers.DictField(),
help_text="Array of log entry dictionaries to append",
)
def validate_entries(self, value):
"""Validate that entries is a non-empty list of dicts"""
if not value:
raise serializers.ValidationError("At least one log entry is required")
return value
class TaskSessionResponseSerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Task session identifier")
download_url = serializers.URLField(allow_null=True, help_text="Temporary URL for downloading the session")
content_sha256 = serializers.CharField(allow_null=True, help_text="SHA-256 digest of the current session content")
class TaskSessionSyncResponseSerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Task session identifier")
content_sha256 = serializers.CharField(help_text="SHA-256 digest of the uploaded session content")
class TaskRunSubscriptionTokenRequestSerializer(serializers.Serializer):
rejected_access_token_sha256 = serializers.RegexField(
r"^[0-9a-f]{64}$",
required=False,
allow_null=True,
default=None,
help_text="SHA-256 hex digest of the access token Codex rejected. The server refreshes only when this "
"names its current token; otherwise it returns the newer token it already holds.",
)
class TaskRunSubscriptionTokenResponseSerializer(serializers.Serializer):
access_token = serializers.CharField(
help_text="ChatGPT access token for the Codex app-server. It can stay valid for several days."
)
account_id = serializers.CharField(help_text="ChatGPT account the access token belongs to")
plan_type = serializers.CharField(allow_null=True, help_text="ChatGPT plan of the account, when known")
expires_at = serializers.DateTimeField(
help_text="When the access token expires. Request a new one before this time."
)
class TaskRunRelayMessageResponseSerializer(serializers.Serializer):
status = serializers.CharField(help_text="Relay status: 'accepted' or 'skipped'")
relay_id = serializers.CharField(required=False, help_text="Relay workflow ID when accepted")
class TaskRunRelayMessageRequestSerializer(serializers.Serializer):
text = serializers.CharField(
max_length=10000,
help_text="Joined message body. Used when text_parts is absent.",
)
message_id = serializers.CharField(
max_length=128,
required=False,
allow_null=True,
help_text="Id of the user message this turn answers, when the agent-server echoes it.",
)
# Kept optional for forward/backward compatibility during rollout; will be aligned once deployed.
text_parts = serializers.ListField(
child=serializers.CharField(max_length=10000, allow_blank=True),
required=False,
allow_empty=True,
help_text="Ordered assistant text blocks. When present, the last non-empty entry is posted instead of text.",
)
trace_id = serializers.UUIDField(
required=False,
allow_null=True,
help_text="AI observability trace id of the turn that wrote this answer, when the sandbox reported one.",
)
class TaskRunArtifactUploadSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255, help_text="File name to associate with the artifact")
type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")
source = serializers.CharField( # type: ignore[assignment]
max_length=64,
required=False,
allow_blank=True,
default="",
help_text="Optional source label for the artifact, such as agent_output or user_attachment",
)
content = serializers.CharField(
trim_whitespace=False,
help_text=(
"Artifact contents encoded according to content_encoding. "
f"Artifacts above {TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES // (1024 * 1024)} MB must use prepare_upload instead."
),
)
content_encoding = serializers.ChoiceField(
choices=TASK_RUN_ARTIFACT_CONTENT_ENCODING_CHOICES,
required=False,
default="utf-8",
help_text="Encoding used for content. Use base64 for binary files and utf-8 for text payloads.",
)
content_type = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
help_text="Optional MIME type for the artifact",
)
metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
attrs = validate_task_run_artifact_metadata(attrs)
content = attrs["content"]
content_encoding = attrs.get("content_encoding", "utf-8")
if content_encoding == "base64":
encoded = content.strip()
if not encoded:
raise serializers.ValidationError({"content": self.fields["content"].error_messages["blank"]})
try:
attrs["content_bytes"] = base64.b64decode(encoded, validate=True)
except (binascii.Error, ValueError) as exc:
raise serializers.ValidationError({"content": "Invalid base64 content"}) from exc
else:
attrs["content_bytes"] = content.encode("utf-8")
max_size_bytes = get_task_run_artifact_inline_max_size_bytes(
attrs.get("name"),
attrs.get("content_type"),
attrs.get("type"),
)
if len(attrs["content_bytes"]) > max_size_bytes:
raise serializers.ValidationError(
{"content": build_task_run_artifact_size_error(attrs.get("name"), max_size_bytes)}
)
return attrs
class TaskRunArtifactsUploadRequestSerializer(serializers.Serializer):
artifacts = TaskRunArtifactUploadSerializer(many=True, help_text="Array of artifacts to upload")
def validate_artifacts(self, value):
if not value:
raise serializers.ValidationError("At least one artifact is required")
return value
class TaskRunArtifactsUploadResponseSerializer(serializers.Serializer):
artifacts = TaskRunArtifactResponseSerializer(many=True, help_text="Updated list of artifacts on the run")
class TaskRunPostHogReferenceSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255, help_text="Fallback display name for the referenced object.")
object_kind = serializers.ChoiceField(
choices=POSTHOG_OBJECT_KIND_CHOICES,
help_text="PostHog object kind used to resolve the reference.",
)
object_id = serializers.CharField(
max_length=16384,
help_text="Exact PostHog object identifier, flag key, event name, or SQL query.",
)
source_message_id = serializers.CharField(
max_length=255,
help_text="Stable identifier of the completed assistant message containing the reference.",
)
class TaskRunPostHogReferencesRequestSerializer(serializers.Serializer):
references = serializers.ListField(
child=TaskRunPostHogReferenceSerializer(),
allow_empty=False,
max_length=50,
help_text="PostHog object references extracted from one completed assistant message.",
)
class TaskRunPostHogReferencesResponseSerializer(serializers.Serializer):
artifacts = TaskRunArtifactResponseSerializer(many=True, help_text="Updated list of artifacts on the run.")
class TaskRunLivingArtifactResponseSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Stable living artifact id. Use this id when editing the artifact.")
task_id = serializers.CharField(help_text="Task id this living artifact belongs to.")
run_id = serializers.CharField(help_text="Task run id that created or currently owns this artifact.")
team_id = serializers.IntegerField(help_text="Project id that owns this artifact.")
name = serializers.CharField(help_text="Human-readable artifact name.")
artifact_type = serializers.ChoiceField(
choices=TASK_RUN_LIVING_ARTIFACT_TYPE_CHOICES,
help_text="Artifact format or delivery surface, such as document, spreadsheet, slack_canvas, file, or slack_message.",
)
adapter = serializers.ChoiceField(
choices=TASK_RUN_LIVING_ARTIFACT_ADAPTER_CHOICES,
help_text="Adapter that currently stores or edits the artifact.",
)
status = serializers.ChoiceField(
choices=[choice for choice, _label in TaskArtifactStatus.choices],
help_text="Current registry status for the artifact.",
)
location = serializers.JSONField(help_text="Adapter-specific location, such as S3 key or Slack canvas id.")
metadata = serializers.JSONField(help_text="Adapter-specific metadata for external storage and source tracking.")
current_version = serializers.IntegerField(help_text="Current version number for the artifact.")
versions = serializers.ListField(
child=serializers.DictField(child=serializers.JSONField()),
help_text="Chronological version records for this artifact.",
)
created_at = serializers.CharField(allow_null=True, required=False, help_text="ISO timestamp when created.")
updated_at = serializers.CharField(allow_null=True, required=False, help_text="ISO timestamp when last updated.")
# drf-spectacular wraps a `list` action response in an array. This endpoint returns one envelope.
@extend_schema_serializer(many=False)
class TaskRunLivingArtifactsResponseSerializer(serializers.Serializer):
artifacts = TaskRunLivingArtifactResponseSerializer(many=True, help_text="Living artifacts for this task run.")
class TaskRunLivingArtifactOpenResponseSerializer(TaskRunLivingArtifactResponseSerializer):
content = serializers.CharField(
allow_null=True,
required=False,
help_text="Current artifact content when the adapter can read it directly.",
)
class TaskRunLivingArtifactCreateRequestSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255, help_text="Human-readable artifact name, used as the title.")
artifact_type = serializers.ChoiceField(
choices=TASK_RUN_LIVING_ARTIFACT_TYPE_CHOICES,
default=TaskArtifactType.DOCUMENT,
help_text="Artifact format or delivery surface to create, such as document, spreadsheet, slack_canvas, or file.",
)
adapter = serializers.ChoiceField(
choices=TASK_RUN_LIVING_ARTIFACT_WRITE_ADAPTER_CHOICES,
required=False,
help_text="Optional preferred external storage or delivery adapter. Slack adapters deliver into the mapped Slack thread; omitted Slack-run documents use Slack canvas, omitted Slack-run files and spreadsheets use Slack file upload, and document_connector uses a connected external document provider.",
)
content = serializers.CharField(
required=False,
allow_blank=True,
trim_whitespace=False,
max_length=500000,
help_text="Markdown or text content for the initial artifact version.",
)
content_base64 = serializers.CharField(
required=False,
allow_blank=False,
help_text="Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run output artifacts.",
)
content_type = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
help_text="MIME type for content_base64 or source-backed artifacts, such as application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.",
)
source_artifact_id = serializers.CharField(
required=False,
allow_blank=True,
help_text="Existing run artifact id to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.",
)
source_storage_path = serializers.CharField(
required=False,
allow_blank=True,
help_text="Existing run artifact storage_path to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.",
)
metadata = serializers.DictField(
child=serializers.JSONField(),
required=False,
default=dict,
help_text="Optional metadata to persist with the living artifact.",
)
def validate(self, attrs):
has_content = "content" in attrs and attrs.get("content") is not None
has_content_base64 = bool(attrs.get("content_base64"))
has_source = bool(attrs.get("source_artifact_id") or attrs.get("source_storage_path"))
if sum([has_content, has_content_base64, has_source]) != 1:
raise serializers.ValidationError(
{
"content": "Provide exactly one of content, content_base64, source_artifact_id, or source_storage_path."
}
)
if has_content_base64:
try:
attrs["content_bytes"] = base64.b64decode(attrs["content_base64"], validate=True)
except (binascii.Error, ValueError) as exc:
raise serializers.ValidationError({"content_base64": "Invalid base64 content"}) from exc
attrs.pop("content_base64", None)
max_size_bytes = get_task_run_artifact_inline_max_size_bytes(
attrs.get("name"),
attrs.get("content_type"),
attrs.get("artifact_type"),
)
if len(attrs["content_bytes"]) > max_size_bytes:
raise serializers.ValidationError(
{"content_base64": build_task_run_artifact_size_error(attrs.get("name"), max_size_bytes)}
)
return attrs
@extend_schema_field(OpenApiTypes.OBJECT)
class InsightQueryJSONField(serializers.JSONField):
"""Insight query JSON — freeform across query kinds, so typed as a plain object."""
class TaskRunLivingArtifactChartRequestSerializer(serializers.Serializer):
name = serializers.CharField(
max_length=255,
help_text="Chart title, also used as the delivered file name.",
)
query = InsightQueryJSONField(
required=False,
help_text=(
"Insight query JSON to render ad hoc, e.g. "
'{"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}. '
"SQL queries (DataVisualizationNode, HogQLQuery) are not supported yet. "
"Provide exactly one of query or insight_id."
),
)
insight_id = serializers.IntegerField(
required=False,
help_text="Numeric id of a saved insight to render. Provide exactly one of query or insight_id.",
)
def validate(self, attrs):
if (attrs.get("query") is None) == (attrs.get("insight_id") is None):
raise serializers.ValidationError({"query": "Provide exactly one of query or insight_id."})
return attrs
class TaskRunLivingArtifactChartResponseSerializer(serializers.Serializer):
artifact = TaskRunLivingArtifactResponseSerializer(help_text="The living artifact registered for delivery.")
export_asset_id = serializers.IntegerField(help_text="Id of the rendered PNG export backing the chart.")
url = serializers.URLField(
allow_null=True,
required=False,
help_text="Link to explore this chart interactively in PostHog.",
)
class TaskRunLivingArtifactEditRequestSerializer(serializers.Serializer):
name = serializers.CharField(
max_length=255,
required=False,
allow_blank=False,
help_text="Optional new human-readable artifact name.",
)
content = serializers.CharField(
required=False,
allow_blank=True,
trim_whitespace=False,
max_length=500000,
help_text="Markdown or text content for the next version.",
)
content_base64 = serializers.CharField(
required=False,
allow_blank=False,
help_text="Base64-encoded binary content for the next version, used by adapters such as slack_file.",
)
content_type = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
help_text="MIME type for content_base64 or source-backed edits.",
)
source_artifact_id = serializers.CharField(
required=False,
allow_blank=True,
help_text="Existing run artifact id to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.",
)
source_storage_path = serializers.CharField(
required=False,
allow_blank=True,
help_text="Existing run artifact storage_path to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.",
)
metadata = serializers.DictField(
child=serializers.JSONField(),
required=False,
default=dict,
help_text="Optional metadata to merge into the artifact registry record.",
)
def validate(self, attrs):
has_content = "content" in attrs and attrs.get("content") is not None
has_content_base64 = bool(attrs.get("content_base64"))
has_source = bool(attrs.get("source_artifact_id") or attrs.get("source_storage_path"))
if sum([has_content, has_content_base64, has_source]) != 1:
raise serializers.ValidationError(
{
"content": "Provide exactly one of content, content_base64, source_artifact_id, or source_storage_path."
}
)
if has_content_base64:
try:
attrs["content_bytes"] = base64.b64decode(attrs["content_base64"], validate=True)
except (binascii.Error, ValueError) as exc:
raise serializers.ValidationError({"content_base64": "Invalid base64 content"}) from exc
attrs.pop("content_base64", None)
max_size_bytes = get_task_run_artifact_inline_max_size_bytes(attrs.get("name"), attrs.get("content_type"))
if len(attrs["content_bytes"]) > max_size_bytes:
raise serializers.ValidationError(
{"content_base64": build_task_run_artifact_size_error(attrs.get("name"), max_size_bytes)}
)
return attrs
class TaskRunArtifactPrepareUploadSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255, help_text="File name to associate with the artifact")
type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")
source = serializers.CharField( # type: ignore[assignment]
max_length=64,
required=False,
allow_blank=True,
default="",
help_text="Optional source label for the artifact, such as agent_output or user_attachment",
)
size = serializers.IntegerField(
min_value=1,
max_value=TASK_RUN_ARTIFACT_MAX_SIZE_BYTES,
help_text=f"Expected upload size in bytes (max {TASK_RUN_ARTIFACT_MAX_SIZE_BYTES} bytes)",
)
content_type = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
help_text="Optional MIME type for the artifact upload",
)
metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs):
attrs = validate_task_run_artifact_metadata(attrs)
max_size_bytes = get_task_run_artifact_max_size_bytes(
attrs.get("name"),
attrs.get("content_type"),
attrs.get("type"),
)
if attrs["size"] > max_size_bytes:
raise serializers.ValidationError(
{"size": build_task_run_artifact_size_error(attrs.get("name"), max_size_bytes)}
)
return attrs
class TaskRunArtifactsPrepareUploadRequestSerializer(serializers.Serializer):
artifacts = TaskRunArtifactPrepareUploadSerializer(many=True, help_text="Array of artifacts to prepare")
def validate_artifacts(self, value):
if not value:
raise serializers.ValidationError("At least one artifact is required")
return value
class S3PresignedPostSerializer(serializers.Serializer):
url = serializers.URLField(help_text="Presigned S3 POST URL")
fields = serializers.DictField( # type: ignore[assignment]
child=serializers.CharField(),
help_text="Form fields that must be submitted verbatim with the file upload",
)
class TaskRunArtifactPrepareUploadResponseSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Stable identifier for the prepared artifact within this run")
name = serializers.CharField(help_text="Artifact file name")
type = serializers.CharField(help_text="Artifact classification (plan, context, etc.)")
source = serializers.CharField( # type: ignore[assignment]
required=False,
allow_blank=True,
help_text="Source of the artifact, such as agent_output or user_attachment",
)
size = serializers.IntegerField(help_text="Expected upload size in bytes")
content_type = serializers.CharField(required=False, allow_blank=True, help_text="Optional MIME type")
metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
storage_path = serializers.CharField(help_text="S3 object key reserved for the artifact")
expires_in = serializers.IntegerField(help_text="Presigned POST expiry in seconds")
presigned_post = S3PresignedPostSerializer(help_text="Presigned S3 POST configuration for uploading the file")
class TaskRunArtifactsPrepareUploadResponseSerializer(serializers.Serializer):
artifacts = TaskRunArtifactPrepareUploadResponseSerializer(
many=True, help_text="Prepared uploads for the requested artifacts"
)
class TaskRunArtifactFinalizeUploadSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Stable identifier returned by the prepare upload endpoint")
name = serializers.CharField(max_length=255, help_text="File name associated with the artifact")
type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")
source = serializers.CharField( # type: ignore[assignment]
max_length=64,
required=False,
allow_blank=True,
default="",
help_text="Optional source label for the artifact, such as agent_output or user_attachment",
)
storage_path = serializers.CharField(max_length=500, help_text="S3 object key returned by the prepare step")
content_type = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
help_text="Optional MIME type recorded for the artifact",
)
metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
base_artifact_id = serializers.CharField(
max_length=255,
required=False,
help_text=(
"ID of the artifact in the same run that this file edits. An HTML edit can run scripts only when "
"its base artifact can."
),
)
def validate(self, attrs):
return validate_task_run_artifact_metadata(attrs)
class TaskRunArtifactsFinalizeUploadRequestSerializer(serializers.Serializer):
artifacts = TaskRunArtifactFinalizeUploadSerializer(many=True, help_text="Array of uploaded artifacts to finalize")
def validate_artifacts(self, value):
if not value:
raise serializers.ValidationError("At least one artifact is required")
return value
class TaskRunArtifactsFinalizeUploadResponseSerializer(serializers.Serializer):
artifacts = TaskRunArtifactResponseSerializer(many=True, help_text="Updated list of artifacts on the run")
class TaskStagedArtifactPrepareUploadSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255, help_text="File name to associate with the staged artifact")
type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")
source = serializers.CharField( # type: ignore[assignment]
max_length=64,
required=False,
allow_blank=True,
default="",
help_text="Optional source label for the artifact, such as agent_output or user_attachment",
)
size = serializers.IntegerField(
min_value=1,
max_value=TASK_RUN_ARTIFACT_MAX_SIZE_BYTES,
help_text=f"Expected upload size in bytes (max {TASK_RUN_ARTIFACT_MAX_SIZE_BYTES} bytes)",
)
content_type = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
help_text="Optional MIME type for the artifact upload",
)
metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs):
attrs = validate_task_run_artifact_metadata(attrs)
max_size_bytes = get_task_run_artifact_max_size_bytes(
attrs.get("name"),
attrs.get("content_type"),
attrs.get("type"),
)
if attrs["size"] > max_size_bytes:
raise serializers.ValidationError(
{"size": build_task_run_artifact_size_error(attrs.get("name"), max_size_bytes)}
)
return attrs
class TaskStagedArtifactsPrepareUploadRequestSerializer(serializers.Serializer):
artifacts = TaskStagedArtifactPrepareUploadSerializer(
many=True, help_text="Array of staged artifacts to prepare before creating a run"
)
def validate_artifacts(self, value):
if not value:
raise serializers.ValidationError("At least one artifact is required")
return value
class TaskStagedArtifactPrepareUploadResponseSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Stable identifier for the prepared staged artifact within this task")
name = serializers.CharField(help_text="Artifact file name")
type = serializers.CharField(help_text="Artifact classification (plan, context, etc.)")
source = serializers.CharField( # type: ignore[assignment]
required=False,
allow_blank=True,
help_text="Source of the artifact, such as agent_output or user_attachment",
)
size = serializers.IntegerField(help_text="Expected upload size in bytes")
content_type = serializers.CharField(required=False, allow_blank=True, help_text="Optional MIME type")
metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
storage_path = serializers.CharField(help_text="S3 object key reserved for the staged artifact")
expires_in = serializers.IntegerField(help_text="Presigned POST expiry in seconds")
presigned_post = S3PresignedPostSerializer(help_text="Presigned S3 POST configuration for uploading the file")
def to_representation(self, instance: Any) -> dict[str, Any]:
data = super().to_representation(instance)
if data.get("metadata") is None:
data.pop("metadata", None)
return data
class TaskStagedArtifactsPrepareUploadResponseSerializer(serializers.Serializer):
artifacts = TaskStagedArtifactPrepareUploadResponseSerializer(
many=True, help_text="Prepared staged uploads for the requested artifacts"
)
class TaskStagedArtifactFinalizeUploadSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Stable identifier returned by the staged prepare upload endpoint")
name = serializers.CharField(max_length=255, help_text="File name associated with the staged artifact")
type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")
source = serializers.CharField( # type: ignore[assignment]
max_length=64,
required=False,
allow_blank=True,
default="",
help_text="Optional source label for the artifact, such as agent_output or user_attachment",
)
storage_path = serializers.CharField(max_length=500, help_text="S3 object key returned by the prepare step")
content_type = serializers.CharField(
max_length=255,
required=False,
allow_blank=True,
help_text="Optional MIME type recorded for the artifact",
)
metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs):
return validate_task_run_artifact_metadata(attrs)
class TaskStagedArtifactsFinalizeUploadRequestSerializer(serializers.Serializer):
artifacts = TaskStagedArtifactFinalizeUploadSerializer(
many=True, help_text="Array of staged artifacts to finalize after upload"
)
def validate_artifacts(self, value):
if not value:
raise serializers.ValidationError("At least one artifact is required")
return value
class TaskStagedArtifactsFinalizeUploadResponseSerializer(serializers.Serializer):
artifacts = TaskRunArtifactResponseSerializer(
many=True, help_text="Finalized staged artifacts available for attachment to a new run"
)
class TaskRunArtifactPresignRequestSerializer(serializers.Serializer):
storage_path = serializers.CharField(
max_length=500,
help_text="S3 storage path returned in the artifact manifest",
)
class TaskRunArtifactPresignResponseSerializer(serializers.Serializer):
url = serializers.URLField(help_text="Presigned URL for downloading the artifact")
expires_in = serializers.IntegerField(help_text="URL expiry in seconds")
class TaskRunArtifactPreviewResponseSerializer(serializers.Serializer):
url = serializers.URLField(help_text="Short-lived URL for the isolated HTML preview")
scripts_available = serializers.BooleanField(
help_text=(
"Whether the caller can request a preview that runs scripts. False when whoever wrote this artifact "
"version had limited network access, or when the version has no record of it."
)
)
class TaskRunArtifactsDismissRequestSerializer(serializers.Serializer):
artifact_ids = serializers.ListField(
child=serializers.CharField(max_length=128),
allow_empty=False,
max_length=100,
help_text=(
"Manifest ids of the artifacts to update. Pass every version of a file together so the "
"whole file is dismissed rather than a single upload of it."
),
)
dismissed = serializers.BooleanField(
default=True,
help_text="True to hide the artifacts from clients, false to show them again.",
)
class TaskRunArtifactsDismissResponseSerializer(serializers.Serializer):
artifacts = TaskRunArtifactResponseSerializer(many=True, help_text="Updated list of artifacts on the run")
class TaskRunAnalyzeResponseSerializer(serializers.Serializer):
analysis_task_id = serializers.UUIDField(help_text="Id of the analysis task to navigate to.")
created = serializers.BooleanField(
help_text="True when a new analysis task was created; false when an existing analysis for this run was returned."
)
class TaskAnalysisGoalKind(models.TextChoices):
ORIENT = "orient", "orient"
EXPLORE = "explore", "explore"
GATHER = "gather", "gather"
PRODUCE = "produce", "produce"
VERIFY = "verify", "verify"
SETUP_ENV = "setup_env", "setup_env"
SHIP = "ship", "ship"
WAIT = "wait", "wait"
OPERATE = "operate", "operate"
DELIVER = "deliver", "deliver"
class TaskAnalysisOutcome(models.TextChoices):
WORKED = "worked", "worked"
FAILED = "failed", "failed"
ABANDONED = "abandoned", "abandoned"
UNKNOWN = "unknown", "unknown"
class TaskAnalysisBlockerKind(models.TextChoices):
MISSING_BINARY = "missing_binary", "missing_binary"
MISSING_PACKAGE = "missing_package", "missing_package"
SERVICE_DOWN = "service_down", "service_down"
MISSING_BUILD_ARTIFACT = "missing_build_artifact", "missing_build_artifact"
MISSING_CREDENTIAL = "missing_credential", "missing_credential"
MEMORY_LIMIT = "memory_limit", "memory_limit"
NETWORK = "network", "network"
SHALLOW_GIT = "shallow_git", "shallow_git"
TOOL_ERROR = "tool_error", "tool_error"
TOOL_SYNTAX = "tool_syntax", "tool_syntax"
API_ERROR = "api_error", "api_error"
MISSING_FLAG = "missing_flag", "missing_flag"
UNCLEAR_INSTRUCTIONS = "unclear_instructions", "unclear_instructions"
USER_REDIRECT = "user_redirect", "user_redirect"
class TaskRunAnalysisActivityRequestSerializer(serializers.Serializer):
"""One activity record from a task-run analysis: what the agent tried, how it went, and what blocked it."""
goal_kind = serializers.ChoiceField(
choices=TaskAnalysisGoalKind.choices, help_text="Which kind of work the agent did in this span."
)
goal = serializers.CharField(min_length=3, max_length=80, help_text="What the agent tried, in 3 to 8 words.")
outcome = serializers.ChoiceField(
choices=TaskAnalysisOutcome.choices, help_text="How the activity ended for the agent."
)
blocker_kind = serializers.ChoiceField(
choices=TaskAnalysisBlockerKind.choices,
required=False,
allow_null=True,
help_text="What stopped the agent, when something did. Omit for healthy work.",
)
blocker_name = serializers.CharField(
max_length=120,
required=False,
allow_null=True,
help_text="The exact binary, package, service, file, flag, or error the blocker names. Required with blocker_kind.",
)
repair = serializers.CharField(
max_length=300,
required=False,
allow_null=True,
help_text="The command or step that removed the blocker, when the agent found one. Requires blocker_kind.",
)
evidence = serializers.CharField(
min_length=10,
max_length=200,
help_text="One exact quote from the run log inside the activity's line range.",
)
start_line = serializers.IntegerField(min_value=1, help_text="First log line of the activity, 1-based.")
end_line = serializers.IntegerField(min_value=1, help_text="Last log line of the activity, 1-based.")
tool_calls = serializers.IntegerField(min_value=0, help_text="Distinct tool calls started inside the line range.")
failed_calls = serializers.IntegerField(
min_value=0, help_text="Tool calls started inside the line range that ended as failed."
)
seconds = serializers.IntegerField(
min_value=0,
help_text="Wall-clock seconds from the last timestamp before the line range to the last timestamp inside it.",
)
idle_seconds = serializers.IntegerField(
min_value=0, help_text="Sum of the gaps longer than 4 minutes between those consecutive timestamps."
)
commands = serializers.ListField(
child=serializers.CharField(min_length=1, max_length=60),
max_length=24,
required=False,
help_text="Command heads run in the activity, in order, adjacent duplicates removed.",
)
guidance_read = serializers.ListField(
child=serializers.CharField(min_length=1, max_length=200),
max_length=20,
required=False,
help_text="Skills, AGENTS.md files, templates, and wiki pages the agent read in the activity.",
)
def validate(self, attrs: dict) -> dict:
if attrs["end_line"] < attrs["start_line"]:
raise serializers.ValidationError("end_line must be greater than or equal to start_line.")
if attrs["failed_calls"] > attrs["tool_calls"]:
raise serializers.ValidationError("failed_calls cannot exceed tool_calls.")
if attrs["idle_seconds"] > attrs["seconds"]:
raise serializers.ValidationError("idle_seconds cannot exceed seconds.")
blocker_kind = attrs.get("blocker_kind")
blocker_name = attrs.get("blocker_name")
if blocker_kind and not blocker_name:
raise serializers.ValidationError("blocker_kind requires blocker_name.")
if blocker_name and not blocker_kind:
raise serializers.ValidationError("blocker_name requires blocker_kind.")
if attrs.get("repair") and not blocker_kind:
raise serializers.ValidationError("repair requires blocker_kind.")
if blocker_name and not _contains_whole_term(attrs["evidence"], blocker_name):
raise serializers.ValidationError("evidence must contain blocker_name as a whole word.")
return attrs
def _contains_whole_term(text: str, term: str) -> bool:
return re.search(rf"(?<![A-Za-z0-9_]){re.escape(term)}(?![A-Za-z0-9_])", text, re.IGNORECASE) is not None
class TaskRunAnalysisActivityResponseSerializer(serializers.Serializer):
activity_index = serializers.IntegerField(help_text="Zero-based position of the stored activity on the run.")
TASK_SUMMARIES_MAX_IDS = 5000
class TaskExecutionMode(models.TextChoices):
INTERACTIVE = "interactive", "interactive"
BACKGROUND = "background", "background"
class TaskSummariesRequestSerializer(serializers.Serializer):
ids = serializers.ListField(
child=serializers.UUIDField(),
allow_empty=False,
max_length=TASK_SUMMARIES_MAX_IDS,
help_text=(
f"Task IDs to fetch summaries for (max {TASK_SUMMARIES_MAX_IDS}). Response is paginated; "
f"follow the `next` cursor to retrieve all results."
),
)
TASK_PULL_REQUEST_TITLES_MAX_IDS = 30
class TaskPullRequestTitlesRequestSerializer(serializers.Serializer):
ids = serializers.ListField(
child=serializers.UUIDField(),
allow_empty=False,
max_length=TASK_PULL_REQUEST_TITLES_MAX_IDS,
help_text=f"Task IDs whose latest run's pull request titles to fetch (max {TASK_PULL_REQUEST_TITLES_MAX_IDS}).",
)
class TaskPullRequestTitlesSerializer(serializers.Serializer):
titles = serializers.DictField(
child=serializers.CharField(),
help_text=(
"Pull request titles keyed by normalized GitHub URL. A pull request is missing when GitHub "
"could not return its title."
),
)
class TaskRunSummarySerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="ID of the latest run.")
status = serializers.ChoiceField(choices=tasks_facade.TaskRunStatus.choices, allow_null=True)
environment = serializers.ChoiceField(choices=tasks_facade.TaskRunEnvironment.choices, allow_null=True)
mode = serializers.ChoiceField(
choices=TaskExecutionMode.choices,
help_text="Execution mode of the latest run.",
)
pr_url = serializers.CharField(
allow_null=True,
help_text="URL of the pull request the latest run opened, or null when it opened none.",
)
pr_state = serializers.ChoiceField(
choices=[*tasks_facade.PR_STATES, "unknown"],
allow_null=True,
help_text=(
"State of that pull request: open, draft, merged, closed, or unknown. "
"Null when the latest run opened no pull request."
),
)
task_summary = serializers.CharField(
allow_null=True,
required=False,
help_text="Latest summary for this task, including a summary inherited from an earlier run.",
)
class TaskSummarySerializer(DataclassSerializer):
"""Summary response for a task — reads from a frozen ``TaskSummaryDTO``."""
created_by_id = serializers.IntegerField(
allow_null=True,
help_text="ID of the user who created the task, or null for system-created tasks.",
)
latest_run = TaskRunSummarySerializer(allow_null=True, required=False)
class Meta:
dataclass = TaskSummaryDTO
fields = [
"id",
"title",
"repository",
"created_by_id",
"created_at",
"updated_at",
"origin_product",
"latest_run",
]
class TaskSourcesListField(RepeatedOrCommaSeparatedListField, JSONTolerantListField):
"""Repeated keys, one comma-joined value (the generated frontend client) or one JSON array (the MCP client).
The base order matters: JSONTolerantListField reads a JSON array before
RepeatedOrCommaSeparatedListField splits on commas. Blank values are dropped, so an empty
value means no source filter, as an empty source list does in the desktop filter.
"""
def get_value(self, dictionary: Any) -> Any:
value = super().get_value(dictionary)
if isinstance(value, list):
return [source for source in value if source != ""]
return value
class SandboxCustomImageListQuerySerializer(serializers.Serializer):
origin_product = serializers.ChoiceField(
required=False,
choices=tasks_facade.TaskOriginProduct.choices,
help_text=(
"Return 403 unless tasks from this origin product can run on custom images. "
"Leave it out to only check that custom images are enabled."
),
)
class TaskListQuerySerializer(serializers.Serializer):
"""Query parameters for listing tasks"""
origin_product = serializers.CharField(required=False, help_text="Filter by origin product")
client_provenance = serializers.ChoiceField(
required=False,
choices=tasks_facade.TaskClientProvenance.choices,
help_text="Filter by the client that created the task",
)
exclude_origin_product = serializers.ChoiceField(
required=False,
choices=tasks_facade.TaskOriginProduct.choices,
help_text="Exclude tasks with this origin product from the results",
)
sources = TaskSourcesListField(
required=False,
child=serializers.ChoiceField(choices=tasks_facade.TaskListSource.choices),
help_text=(
"Only tasks from any of these sources. Repeat the parameter for each source, or send one "
"comma-joined value or a JSON array. 'posthog_desktop', 'posthog_mobile' and 'posthog_web' "
"match user-created tasks by the client that created them, and a user-created task from no "
"other known client counts as desktop. 'posthog_web' also matches PostHog AI tasks. "
"Any other value matches the task's origin product."
),
)
stage = serializers.CharField(required=False, help_text="Filter by task run stage")
organization = serializers.CharField(required=False, help_text="Filter by repository organization")
repository = serializers.CharField(
required=False, help_text="Filter by repository name (can include org/repo format)"
)
created_by = serializers.IntegerField(required=False, help_text="Filter by creator user ID")
basic = serializers.BooleanField(
required=False,
default=False,
help_text=(
"With true, return basic list rows for summary surfaces: each row omits the full description "
"and includes description_preview, its first 1000 characters. Defaults to false, which returns "
"full task rows with description. The search parameter still matches description text server-side."
),
)
search = serializers.CharField(
required=False,
allow_blank=True,
help_text="Case-insensitive substring search over task title and description. A numeric value also matches the task number. An empty value disables the filter.",
)
status = serializers.ChoiceField(
required=False,
choices=[choice.value for choice in tasks_facade.TaskRunStatus],
help_text="Filter tasks by the status of their most recent run.",
)
pr_state = serializers.ChoiceField(
required=False,
choices=list(tasks_facade.PR_STATES),
help_text=(
"Filter tasks by the state of their most recent run's pull request, as last observed "
"from GitHub (webhooks plus the CI follow-up snapshot)."
),
)
ci_status = serializers.ChoiceField(
required=False,
choices=list(tasks_facade.CI_STATUSES),
help_text=(
"Filter tasks by the CI check rollup on their most recent run's pull request, as last "
"observed from GitHub. 'none' means the PR has no checks."
),
)
pinned = serializers.BooleanField(
required=False,
help_text="With true, only tasks the requesting user has pinned.",
)
commented_by = serializers.IntegerField(
required=False,
help_text="Filter to tasks carrying a thread comment written by this user ID.",
)
mentions = serializers.IntegerField(
required=False,
help_text="Filter to tasks whose thread mentions this user ID.",
)
internal = serializers.ChoiceField(
required=False,
choices=["true", "false", "all"],
help_text=(
"Filter by the internal flag, which controls whether a task is shown by default, not whether "
"it is accessible. Defaults to excluding internal tasks. Use 'all' to include both internal "
"and user-facing tasks, or 'true' to list only internal tasks. All values are available to any "
"team member; access stays governed by task visibility."
),
)
archived = serializers.ChoiceField(
required=False,
choices=["true", "false", "all"],
help_text=(
"Filter by archived state. Defaults to excluding archived tasks. Use 'true' to list only "
"archived tasks, 'false' for the default, or 'all' to include both."
),
)
channel = serializers.UUIDField(required=False, help_text="Filter tasks to a channel's feed.")
hog_flow_id = serializers.UUIDField(
required=False, help_text="Filter tasks to the runs spawned by this workflow's 'Create AI task' action."
)
ordering = serializers.ChoiceField(
required=False,
choices=sorted(tasks_facade.TASK_LIST_ORDERINGS),
help_text=(
"Sort order. '-last_activity_at' is newest activity first, where activity means a thread "
"message or a run starting, streaming, or finishing. Defaults to '-created_at'."
),
)
all_team_tasks = serializers.BooleanField(
required=False,
default=False,
help_text=(
"Local development only. With ph_debug=true, list all project tasks for debugging. "
"Ignored outside local development."
),
)
class TaskSearchQuerySerializer(serializers.Serializer):
q = serializers.CharField(min_length=1, max_length=512, help_text="Text or exact identifier to search for.")
limit = serializers.IntegerField(
required=False, default=20, min_value=1, max_value=50, help_text="Maximum number of results to return."
)
class TaskSearchResultSerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Search document identifier.")
kind = serializers.ChoiceField(
choices=["task", "pull_request", "artifact", "channel", "canvas"], help_text="Type of matched resource."
)
title = serializers.CharField(help_text="Primary result label.")
subtitle = serializers.CharField(allow_blank=True, help_text="Secondary result context.")
task_id = serializers.UUIDField(allow_null=True, help_text="Containing task identifier, when applicable.")
task_run_id = serializers.UUIDField(allow_null=True, help_text="Containing task run identifier, when applicable.")
channel_id = serializers.UUIDField(allow_null=True, help_text="Containing space identifier, when applicable.")
created_by = TaskUserBasicInfoSerializer(
allow_null=True, help_text="Who created the containing task, when the match has one."
)
origin_product = serializers.CharField(
allow_null=True, allow_blank=True, help_text="What created the containing task, for example 'slack'."
)
latest_run = TaskRunSummarySerializer(allow_null=True, help_text="Status of the containing task's most recent run.")
updated_at = serializers.DateTimeField(help_text="When the matched resource last changed.")
metadata = serializers.JSONField(help_text="Resource-specific navigation metadata.")
class ChannelSerializer(DataclassSerializer):
"""Response shape for a task channel, read from a frozen ``ChannelDTO``."""
created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
system_role = serializers.ChoiceField(
choices=tasks_facade.Channel.SystemRole.choices,
allow_null=True,
read_only=True,
help_text=(
"Identifies this channel as one of the two system-provisioned spaces "
"('personal' for the user's own #me space, 'general' for the team's "
"shared #general space). Null for an ordinary channel."
),
)
class Meta:
dataclass = ChannelDTO
fields = [
"id",
"name",
"channel_type",
"github_integration",
"repositories",
"auto_archive_after_days",
"created_at",
"created_by",
"starred",
"system_role",
]
class ChannelPageSerializer(serializers.Serializer):
count = serializers.IntegerField(help_text="Number of channels the requester can access.")
next = serializers.URLField(allow_null=True, help_text="URL of the next page, or null on the last page.")
previous = serializers.URLField(allow_null=True, help_text="URL of the previous page, or null on the first page.")
results = ChannelSerializer(many=True, help_text="Channels on this page.")
# The channel list is an array without `limit` and a page with `limit`, so its schema is one of the two.
ChannelListResponseSerializer = PolymorphicProxySerializer(
component_name="ChannelListResponse",
serializers=[ChannelSerializer(many=True), ChannelPageSerializer],
resource_type_field_name=None,
many=False,
)
class ChannelContributorsSerializer(DataclassSerializer):
"""The people who own at least one task or canvas in a channel."""
channel = serializers.UUIDField(help_text="The channel these people worked in.")
people = TaskUserBasicInfoSerializer(
many=True,
help_text=(
"Everyone who owns at least one task or canvas in the channel, most recently active first. "
"Deleted tasks and canvases do not count."
),
)
class Meta:
dataclass = ChannelContributorsDTO
fields = ["channel", "people"]
class OnboardingSessionSerializer(serializers.Serializer):
"""The first-run session that was started for the requester."""
task_id = serializers.UUIDField(help_text="The agent session opened in the team's #general space.")
class OnboardingSessionTestResponseSerializer(OnboardingSessionSerializer):
channel_id = serializers.UUIDField(help_text="The requester's personal space containing the session.")
class OnboardingSessionTestSerializer(serializers.Serializer):
model = serializers.CharField(
required=False,
default=None,
allow_null=True,
allow_blank=False,
max_length=255,
help_text="Optional LLM model identifier for the test session. Omit to use the plan default.",
)
company_domain = serializers.CharField(
required=False,
default="",
allow_blank=True,
max_length=253,
help_text="Company domain to research. Blank simulates a personal email address.",
)
joining_existing_organization = serializers.BooleanField(
default=False,
help_text="Whether the user is joining an organization that already has shared context.",
)
has_events = serializers.BooleanField(default=False, help_text="Whether the project has ingested events.")
signal_reports_waiting = serializers.IntegerField(
default=0, min_value=0, max_value=10000, help_text="Number of findings waiting in #general."
)
other_members = serializers.ListField(
child=serializers.CharField(max_length=100),
default=list,
max_length=25,
help_text="Display names of other Desktop users in the organization.",
)
sources_enabled = serializers.ListField(
child=serializers.CharField(max_length=100),
default=list,
max_length=25,
help_text="Signal sources that were already enabled.",
)
sources_watching = serializers.ListField(
child=serializers.CharField(max_length=100),
default=list,
max_length=25,
help_text="Signal sources the onboarding flow is watching.",
)
sources_newly_enabled = serializers.BooleanField(
default=False, help_text="Whether onboarding enabled any signal sources."
)
def validate_model(self, value: str | None) -> str | None:
model_access_error = get_model_access_error(value, distinct_id=request_distinct_id(self.context))
if model_access_error is not None:
raise serializers.ValidationError(model_access_error)
if value is not None and get_runtime_adapter_for_model(value) is None:
raise serializers.ValidationError(f"'{value}' is not supported for onboarding test sessions.")
return value
class TeachingCanvasSerializer(serializers.Serializer):
canvas_id = serializers.UUIDField(help_text="The teaching canvas that was resolved or created.")
channel_id = serializers.UUIDField(help_text="The requester's personal space containing the canvas.")
class ProvisionedChannelsSerializer(serializers.Serializer):
"""The requester's default channels, plus whether this call is what created them."""
channels = ChannelSerializer(
many=True,
help_text="The full channel list after provisioning, same shape as the list endpoint.",
)
personal_created = serializers.BooleanField(
help_text="Whether this call created the requester's personal #me channel."
)
general_created = serializers.BooleanField(
help_text=(
"Whether this call created the team's shared #general channel. True only for "
"the first user to provision it, so clients can branch first-user setup on it."
)
)
class ChannelDeleteConflictSerializer(serializers.Serializer):
detail = serializers.CharField(help_text="Why the space cannot be deleted.")
CHANNEL_MEMBERS_MAX = 100
class ChannelWriteSerializer(serializers.Serializer):
name = serializers.CharField(
max_length=128, help_text="Channel name, shown as #<name>. Uses lowercase letters and hyphens."
)
channel_type = serializers.ChoiceField(
choices=TaskChannelWriteType.choices,
default="public",
help_text=(
"Use 'public' for access by all project members. Use 'private' for access by channel members only. "
"Defaults to 'public'. This endpoint cannot create personal #me spaces."
),
)
member_ids = serializers.ListField(
child=serializers.IntegerField(),
required=False,
default=list,
max_length=CHANNEL_MEMBERS_MAX,
help_text=(
"User IDs to add to a private channel. The requester is always a member. "
"The endpoint ignores this field for public channels and skips users without project access."
),
)
star = serializers.BooleanField(
required=False,
default=True,
help_text=("Star a new channel for the requester. This field does not change stars on an existing channel."),
)
def validate_name(self, value: str) -> str:
if tasks_facade.is_personal_space_name(value):
raise serializers.ValidationError("That name is reserved for private spaces. Pick another name.")
return value
class ChannelMembersWriteSerializer(serializers.Serializer):
user_ids = serializers.ListField(
child=serializers.IntegerField(),
allow_empty=True,
max_length=CHANNEL_MEMBERS_MAX,
help_text=(
"Required list of member user IDs. This list replaces the current members. "
"The creator remains a member. Send an empty list to remove all other members. "
"Each submitted user must have project access."
),
)
class ChannelUpdateSerializer(serializers.Serializer):
name = serializers.CharField(
max_length=128,
required=False,
help_text="Channel name, rendered as #<name>. Normalized to lowercase-dashed.",
)
github_integration = IntegrationReferenceField(
kinds=["github"],
required=False,
allow_null=True,
help_text="Team GitHub integration used for repositories linked to this channel.",
)
repositories = serializers.ListField(
child=serializers.CharField(max_length=255),
required=False,
max_length=10,
help_text="GitHub repositories inherited by new tasks in this channel.",
)
auto_archive_after_days = serializers.IntegerField(
required=False,
allow_null=True,
min_value=1,
max_value=365,
help_text="Days of inactivity before tasks in this channel are archived. Accepts 1 through 365. Null disables automatic archiving.",
)
channel_type = serializers.ChoiceField(
choices=TaskChannelWriteType.choices,
required=False,
help_text=(
"Switch a shared space between 'public' and 'private'. Making a space private keeps only the creator "
"and the requester as members. Making it public removes its member list. Personal #me spaces cannot change."
),
)
def validate_name(self, value: str) -> str:
if tasks_facade.is_reserved_channel_name(value):
raise serializers.ValidationError("That name is reserved for a default space. Pick another name.")
return value
def validate_repositories(self, value: list[str]) -> list[str]:
repositories = [TaskWriteSerializer().validate_repository(repository) for repository in value]
if len(set(repositories)) != len(repositories):
raise serializers.ValidationError("Repositories must be unique")
return repositories
def validate(self, attrs: dict) -> dict:
repositories = attrs.get("repositories")
integration = attrs.get("github_integration")
if repositories is None:
if "github_integration" in attrs:
raise serializers.ValidationError({"repositories": "Required when changing the GitHub integration"})
return attrs
if repositories and integration is None:
raise serializers.ValidationError({"github_integration": "Required when repositories are configured"})
if repositories and integration:
inaccessible = tasks_facade.inaccessible_repositories_via_integration(
self.context["team_id"], integration.id, repositories
)
if inaccessible:
raise serializers.ValidationError(
{"repositories": f"Not accessible via the selected GitHub integration: {', '.join(inaccessible)}"}
)
return attrs
class ChannelInstructionsSerializer(DataclassSerializer):
"""Response shape for a channel's CONTEXT.md instructions version."""
created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
class Meta:
dataclass = ChannelInstructionsDTO
fields = ["channel", "content", "version", "created_at", "created_by"]
class ChannelInstructionsWriteSerializer(serializers.Serializer):
"""Request body for publishing a new instructions version."""
content = serializers.CharField(
allow_blank=True,
trim_whitespace=False,
max_length=CHANNEL_INSTRUCTIONS_MAX_BYTES,
help_text="The complete markdown instructions (CONTEXT.md) for the channel.",
)
base_version = serializers.IntegerField(
required=False,
allow_null=True,
min_value=0,
help_text=(
"Optimistic-concurrency guard: the version the edit is based on (0 for a channel with no "
"instructions yet). A stale base is rejected with 409; omit to publish unguarded."
),
)
class ChannelContextGenerationSerializer(serializers.Serializer):
"""The task currently generating this channel's CONTEXT.md, or null."""
task_id = serializers.UUIDField(allow_null=True)
class SpaceSetupKind(models.TextChoices):
GOAL = "goal", "Goal"
FEATURE = "feature", "Feature"
class SpaceGoalDirection(models.TextChoices):
AT_LEAST = "at_least", "At least"
AT_MOST = "at_most", "At most"
class SpaceGoalPeriod(models.TextChoices):
DAY = "day", "Day"
WEEK = "week", "Week"
MONTH = "month", "Month"
class SpaceGoalWriteSerializer(serializers.Serializer):
"""The metric a goal space should move."""
statement = serializers.CharField(
max_length=2000, help_text="The goal in one or two sentences, e.g. 'Increase the weekly activation rate'."
)
period = serializers.ChoiceField(
choices=SpaceGoalPeriod.choices, default=SpaceGoalPeriod.WEEK, help_text="How often the metric is measured."
)
direction = serializers.ChoiceField(
choices=SpaceGoalDirection.choices,
default=SpaceGoalDirection.AT_LEAST,
help_text="Whether the target is a floor ('at_least') or a ceiling ('at_most').",
)
target = serializers.CharField(
max_length=64,
required=False,
allow_null=True,
allow_blank=True,
help_text="Target value as typed, e.g. '20%' or '1500'.",
)
deadline = serializers.DateField(required=False, allow_null=True, help_text="Date the target should be reached.")
insight_short_id = serializers.CharField(
max_length=64,
required=False,
allow_null=True,
allow_blank=True,
help_text="Short id of an existing insight that measures the goal, when there is one.",
)
class SpaceFeatureWriteSerializer(serializers.Serializer):
"""The feature a feature space is set up around."""
name = serializers.CharField(max_length=200, help_text="Feature name as people call it.")
description = serializers.CharField(
max_length=2000, required=False, allow_blank=True, default="", help_text="What the feature does, in a sentence."
)
flag_key = serializers.CharField(
max_length=400,
required=False,
allow_null=True,
allow_blank=True,
help_text="Key of the feature flag that gates it, if any.",
)
def _blank_to_none(data: dict, *, keep: frozenset[str] = frozenset()) -> dict:
"""Optional text fields arrive as "" from a form; the contracts use None for "not given"."""
return {key: (None if value == "" and key not in keep else value) for key, value in data.items()}
class ChannelSetupWriteSerializer(serializers.Serializer):
"""Request body for starting the task that sets a space up for a goal or a feature."""
kind = serializers.ChoiceField(choices=SpaceSetupKind.choices, help_text="What the space is set up for.")
goal = SpaceGoalWriteSerializer(required=False, help_text="Required when kind is 'goal'.")
feature = SpaceFeatureWriteSerializer(required=False, help_text="Required when kind is 'feature'.")
repository = serializers.CharField(
max_length=255,
required=False,
allow_null=True,
allow_blank=True,
help_text="Repository the loops work in, as 'owner/name'. Defaults to the channel's first repository.",
)
def validate(self, attrs: dict) -> dict:
kind = attrs["kind"]
if kind == SpaceSetupKind.GOAL and not attrs.get("goal"):
raise serializers.ValidationError({"goal": "A goal setup needs a goal."})
if kind == SpaceSetupKind.FEATURE and not attrs.get("feature"):
raise serializers.ValidationError({"feature": "A feature setup needs a feature."})
return attrs
def to_request(self) -> SpaceSetupRequest:
data = self.validated_data
goal = data.get("goal")
feature = data.get("feature")
return SpaceSetupRequest(
kind=data["kind"],
goal=SpaceGoalRequest(**_blank_to_none(goal)) if goal else None,
feature=SpaceFeatureRequest(**_blank_to_none(feature, keep=frozenset({"description"})))
if feature
else None,
repository=data.get("repository") or None,
)
class ChannelSetupResponseSerializer(DataclassSerializer):
"""The setup task that was started for the channel."""
class Meta:
dataclass = SpaceSetupStartedDTO
fields = ["task_id"]
class ChannelStarWriteSerializer(serializers.Serializer):
"""Request body for starring/unstarring a channel for the requesting user."""
starred = serializers.BooleanField()
class TaskThreadMessageSerializer(DataclassSerializer):
"""Response shape for one message in a task's thread."""
author = TaskUserBasicInfoSerializer(allow_null=True, required=False)
forwarded_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
class Meta:
dataclass = TaskThreadMessageDTO
fields = [
"id",
"task",
"author_kind",
"event",
"payload",
"content",
"created_at",
"author",
"forwarded_to_agent_at",
"forwarded_by",
]
class TaskThreadMessageWriteSerializer(serializers.Serializer):
"""Request body for posting a thread message."""
content = serializers.CharField(help_text="Message text.")
# The lifecycle events a client may post into a channel's feed. Kept narrow so the
# feed stays a curated set of announcements, not an open write surface.
CHANNEL_FEED_EVENTS = ["context_created", "context_md_building"]
class ChannelFeedMessageSerializer(DataclassSerializer):
"""Response shape for one system announcement in a channel's feed."""
author = TaskUserBasicInfoSerializer(allow_null=True, required=False)
class Meta:
dataclass = ChannelFeedMessageDTO
fields = ["id", "channel", "author", "author_kind", "event", "payload", "content", "created_at"]
# A client-supplied created_at exists only to order a burst of announcements posted
# in quick succession; anything beyond this window is backdating, not ordering.
CHANNEL_FEED_CREATED_AT_WINDOW = timedelta(minutes=10)
# Feed payloads carry a couple of short strings (e.g. a context name); the cap stops one
# member storing megabytes of JSON every reader must then load and serialize.
CHANNEL_FEED_PAYLOAD_MAX_BYTES = 8 * 1024
class ChannelFeedMessageWriteSerializer(serializers.Serializer):
"""Request body for posting a system announcement into a channel's feed."""
event = serializers.ChoiceField(choices=CHANNEL_FEED_EVENTS, help_text="Lifecycle event key.")
payload = serializers.JSONField(
required=False,
default=dict,
help_text='Structured event data, e.g. {"context_name": "mobile"}. At most 8 KB of JSON.',
)
created_at = serializers.DateTimeField(
required=False,
help_text="Optional explicit timestamp (within 10 minutes of now), so a client can order a burst of announcements.",
)
def validate_created_at(self, value: datetime) -> datetime:
if abs(django_timezone.now() - value) > CHANNEL_FEED_CREATED_AT_WINDOW:
raise serializers.ValidationError("created_at must be within 10 minutes of the current time.")
return value
def validate_payload(self, value: dict) -> dict:
if not isinstance(value, dict):
raise serializers.ValidationError("payload must be a JSON object.")
if len(json.dumps(value)) > CHANNEL_FEED_PAYLOAD_MAX_BYTES:
raise serializers.ValidationError("payload must be at most 8 KB of JSON.")
return value
class TaskMentionQuerySerializer(serializers.Serializer):
"""Query parameters for listing mentions."""
since = serializers.DateTimeField(
required=False, help_text="Only return mentions created after this ISO 8601 timestamp."
)
limit = serializers.IntegerField(
required=False,
default=100,
min_value=1,
max_value=500,
help_text="Maximum number of mentions to return (newest first).",
)
class TaskMentionSerializer(DataclassSerializer):
"""Response shape for one @-mention of the requester in a task's thread."""
author = TaskUserBasicInfoSerializer(allow_null=True, required=False)
class Meta:
dataclass = TaskMentionDTO
fields = [
"id",
"message_id",
"task_id",
"task_title",
"channel_id",
"channel_name",
"author",
"content",
"created_at",
]
class TaskActivityQuerySerializer(serializers.Serializer):
"""Query parameters for the task-centric activity feed."""
limit = serializers.IntegerField(
required=False,
default=100,
min_value=1,
max_value=500,
help_text="Maximum number of tasks to return (most recent activity first).",
)
before = serializers.DateTimeField(
required=False,
help_text="Activity timestamp from the final row of the previous page.",
)
before_id = serializers.UUIDField(
required=False,
help_text="Activity ID from the final row of the previous page.",
)
def validate(self, attrs):
if ("before" in attrs) != ("before_id" in attrs):
raise serializers.ValidationError("before and before_id must be provided together")
return attrs
class TaskActivitySerializer(DataclassSerializer):
"""Response shape for one task in the requester's activity feed (one row per task)."""
latest_author = TaskUserBasicInfoSerializer(
allow_null=True,
required=False,
help_text="Author of the thread message tied to the latest activity, when one applies.",
)
activity_kind = serializers.ChoiceField(
choices=[
"awaiting_input",
"completed",
"mention",
"thread_reply",
"owned_item_comment",
"message",
"created",
],
help_text=(
"What the latest activity on this task was: an agent run waiting on the requester "
"(awaiting_input), a completed run (completed), someone @-mentioning them (mention), "
"a comment-thread reply (thread_reply), a comment on their item (owned_item_comment), "
"a task-thread reply (message), or their creating the task (created)."
),
)
snippet = serializers.CharField(
help_text="Content of the thread message or resource comment tied to the latest activity."
)
is_unread = serializers.BooleanField(
help_text="Whether the requester has yet to see this activity. Activity they caused themselves is never unread."
)
class Meta:
dataclass = TaskActivityDTO
fields = [
"id",
"task_id",
"task_title",
"channel_id",
"channel_name",
"activity_at",
"activity_kind",
"snippet",
"latest_author",
"latest_message_id",
"latest_comment_id",
"latest_comment_scope",
"latest_comment_item_id",
"is_unread",
]
class TaskActivityPageSerializer(DataclassSerializer):
"""A page of the requester's activity feed, plus the unread total across the whole feed."""
results = TaskActivitySerializer(many=True, help_text="Tasks with activity, most recent first.")
unread_count = serializers.IntegerField(
help_text="Unread tasks across the requester's whole feed, not just this page. Backs the sidebar badge."
)
next_before = serializers.DateTimeField(
allow_null=True,
required=False,
help_text="Activity timestamp to pass as before for the next page, or null on the final page.",
)
next_before_id = serializers.UUIDField(
allow_null=True,
required=False,
help_text="Activity ID to pass as before_id for the next page, or null on the final page.",
)
next = serializers.URLField(
read_only=True,
allow_null=True,
default=None,
help_text="URL of the next page, with before and before_id set, or null on the final page.",
)
previous = serializers.URLField(
read_only=True,
allow_null=True,
default=None,
help_text="Always null: the feed pages forward only.",
)
class Meta:
dataclass = TaskActivityPageDTO
fields = ["results", "unread_count", "next_before", "next_before_id", "next", "previous"]
class TaskActivityReadMarkerSerializer(serializers.Serializer):
task_id = serializers.UUIDField(
required=False,
allow_null=True,
help_text="Task whose displayed activity should be marked read. Optional when activity_id is set.",
)
activity_id = serializers.UUIDField(
required=False,
allow_null=True,
help_text="Comment activity row to mark read. Omit for collapsed task activity.",
)
seen_before = serializers.DateTimeField(
help_text="Mark activity at or before this timestamp read without clearing newer activity."
)
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
if not attrs.get("task_id") and not attrs.get("activity_id"):
raise serializers.ValidationError("Set task_id or activity_id.")
return attrs
class TaskActivityMarkReadSerializer(serializers.Serializer):
"""Request body for clearing the unread flag on specific tasks."""
activities = serializers.ListField(
child=TaskActivityReadMarkerSerializer(),
allow_empty=False,
max_length=500,
help_text="Displayed task activities to mark read if they have not changed.",
)
class TaskActivityMarkReadResponseSerializer(serializers.Serializer):
marked_read = serializers.IntegerField(help_text="How many feed rows changed from unread to read.")
unread_count = serializers.IntegerField(help_text="The requester's remaining unread total after the update.")
class TaskRepositoriesResponseSerializer(serializers.Serializer):
repositories = serializers.ListField(
child=serializers.CharField(),
help_text="Distinct repositories in use by non-deleted, non-internal tasks for the current team.",
)
class TaskSourcesResponseSerializer(serializers.Serializer):
sources = serializers.ListField(
child=serializers.ChoiceField(choices=tasks_facade.TaskListSource.choices),
help_text=(
"Distinct sources of the requester's own non-archived tasks, sorted, in the words of the task "
"list `sources` filter. Each value filters the task list back to at least one task."
),
)
class TaskArtifactSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Stable artifact id used to filter task comments.")
type = serializers.CharField(help_text="Artifact type: artifact or canvas.")
name = serializers.CharField(help_text="Display name of the artifact.")
class TaskArtifactsResponseSerializer(serializers.Serializer):
artifacts = TaskArtifactSerializer(many=True, help_text="Artifacts and canvases linked to this task.")
class TaskUsageResponseSerializer(serializers.Serializer):
token_cost_usd = serializers.FloatField(help_text="Estimated model cost attributed to this task in US dollars.")
compute_cost_usd = serializers.FloatField(
help_text="Estimated cloud compute cost attributed to this task in US dollars."
)
total_cost_usd = serializers.FloatField(help_text="Estimated total cost attributed to this task in US dollars.")
class InternalTaskUsageRequestSerializer(serializers.Serializer):
team_id = serializers.IntegerField(help_text="Team identifier used to scope attributed model generations.")
task_id = serializers.UUIDField(help_text="Task identifier used to attribute model generations.")
task_created_at = serializers.DateTimeField(help_text="Lower timestamp bound for attributed model generations.")
class InternalTaskUsageResponseSerializer(serializers.Serializer):
token_cost_usd = serializers.FloatField(help_text="Estimated model cost attributed to this task in US dollars.")
class TaskCommentsQuerySerializer(serializers.Serializer):
artifact_id = serializers.CharField(
required=False, max_length=72, help_text="Artifact id returned by the artifacts endpoint."
)
include_resolved = serializers.BooleanField(
required=False,
default=False,
help_text="Whether to include resolved comment threads.",
)
limit = serializers.IntegerField(
required=False,
default=50,
min_value=1,
max_value=100,
help_text="Maximum number of root comments to return.",
)
cursor = serializers.CharField(
required=False, max_length=256, help_text="Opaque cursor returned by the previous page."
)
class TaskCommentDetailQuerySerializer(serializers.Serializer):
limit = serializers.IntegerField(
required=False,
default=50,
min_value=1,
max_value=100,
help_text="Maximum number of comments in the thread to return.",
)
cursor = serializers.CharField(
required=False, max_length=256, help_text="Opaque cursor returned by the previous page."
)
comment_id = serializers.UUIDField(
required=False,
help_text="Comment id whose truncated body should continue. Use with content_offset.",
)
content_offset = serializers.IntegerField(
required=False,
default=0,
min_value=0,
help_text="Byte offset returned as content_next_offset for the selected comment.",
)
def validate(self, attrs: dict) -> dict:
if attrs.get("content_offset") and not attrs.get("comment_id"):
raise serializers.ValidationError({"comment_id": "This field is required with content_offset."})
if attrs.get("comment_id") and attrs.get("cursor"):
raise serializers.ValidationError({"cursor": "Do not combine cursor with comment_id."})
return attrs
class TaskCommentTargetSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Stable target id.")
type = serializers.CharField(help_text="Target type: task, artifact, canvas, preview, or browser.")
name = serializers.CharField(help_text="Display name of the comment target.")
class TaskCommentSummarySerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Root comment id.")
target = TaskCommentTargetSerializer(
help_text="Task, artifact, canvas, preview, or in-app browser page receiving the comment."
)
content = serializers.CharField(help_text="Bounded excerpt of the root comment body.")
content_truncated = serializers.BooleanField(help_text="Whether the root comment body has more content.")
selected_text = serializers.CharField(allow_null=True, help_text="Text selected when the comment was created.")
created_at = serializers.DateTimeField(help_text="When the root comment was created.")
reply_count = serializers.IntegerField(help_text="Number of human replies.")
resolved = serializers.BooleanField(help_text="Whether the comment is resolved.")
class TaskCommentsResponseSerializer(serializers.Serializer):
comments = TaskCommentSummarySerializer(many=True, help_text="Root comments, newest first.")
next = serializers.CharField(allow_null=True, help_text="Opaque cursor for the next page, or null.")
class TaskCommentAnchorSerializer(serializers.Serializer):
kind = serializers.CharField(required=False, help_text="Anchor kind.")
quote = serializers.CharField(required=False, help_text="Selected text.")
prefix = serializers.CharField(required=False, help_text="Text immediately before the selection.")
suffix = serializers.CharField(required=False, help_text="Text immediately after the selection.")
start = serializers.IntegerField(required=False, min_value=0, help_text="Selection start offset.")
end = serializers.IntegerField(required=False, min_value=1, help_text="Selection end offset.")
x = serializers.FloatField(required=False, min_value=0, max_value=1, help_text="Horizontal region position.")
y = serializers.FloatField(required=False, min_value=0, max_value=1, help_text="Vertical region position.")
width = serializers.FloatField(required=False, min_value=0, max_value=1, help_text="Region width.")
height = serializers.FloatField(required=False, min_value=0, max_value=1, help_text="Region height.")
class TaskCommentEntrySerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Comment id.")
content = serializers.CharField(help_text="Byte-bounded comment body chunk.")
content_truncated = serializers.BooleanField(help_text="Whether this comment body has more content.")
content_next_offset = serializers.IntegerField(
allow_null=True,
help_text="Byte offset for the next body chunk, or null when complete.",
)
author = serializers.CharField(allow_null=True, help_text="Comment author's display name.")
created_at = serializers.DateTimeField(help_text="When the comment was created.")
anchor = TaskCommentAnchorSerializer(allow_null=True, help_text="Normalized text or document anchor.")
canvas_version_id = serializers.CharField(allow_null=True, help_text="Canvas version receiving the comment.")
class TaskCommentDetailSerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Root comment id.")
target = TaskCommentTargetSerializer(
help_text="Task, artifact, canvas, preview, or in-app browser page receiving the comment."
)
resolved = serializers.BooleanField(help_text="Whether the comment is resolved.")
comments = TaskCommentEntrySerializer(many=True, help_text="Comments in this page, oldest first.")
next = serializers.CharField(allow_null=True, help_text="Opaque cursor for the next page, or null.")
class PinnedTaskIdsResponseSerializer(serializers.Serializer):
task_ids = serializers.ListField(
child=serializers.UUIDField(),
help_text="Visible task IDs pinned by the requester, newest pin first.",
)
class TaskPinRequestSerializer(serializers.Serializer):
pinned = serializers.BooleanField(help_text="Whether the task should be pinned for the requester.")
class TaskHandoffRequestSerializer(serializers.Serializer):
"""Request body for handing a task off to a colleague: they become its owner."""
user = serializers.IntegerField(
min_value=1,
help_text=(
"ID of the user taking over the task. Must have access to this project and not be the task's current owner."
),
)
class TaskPinResponseSerializer(serializers.Serializer):
task_id = serializers.UUIDField(help_text="Task whose pin state was updated.")
pinned = serializers.BooleanField(help_text="Current pin state for the requester.")
class ModelChoiceSerializer(DataclassSerializer):
"""One model a run may use. Reads a `ModelChoice` straight off the catalogue facade.
Both enums are declared with the same choices the run-detail response uses, so clients get the
generated adapter/effort types here rather than bare strings.
"""
runtime_adapter = serializers.ChoiceField(
choices=RuntimeAdapter.choices,
help_text="Runtime that drives this model, such as 'claude' or 'codex'.",
)
display_name = serializers.CharField(
source="label", help_text="Display name for the model, such as 'Claude Opus 4.8'."
)
supported_efforts = serializers.ListField(
child=serializers.ChoiceField(choices=list(REASONING_EFFORTS)),
help_text="Reasoning efforts this model accepts, in ascending order. Empty for a model with no effort control.",
)
cost_multiplier = serializers.CharField(
allow_null=True,
required=False,
help_text=(
"Per-token cost against the catalogue baseline, ready to display, such as '2.5x' or "
"'~0.55x'. Prefixed when the input and output rates diverge enough that one number "
"flatters either. Null for a model the catalogue quotes no rate for."
),
)
class Meta:
dataclass = ModelChoice
fields = ["runtime_adapter", "model", "display_name", "supported_efforts", "cost_multiplier"]
class ModelCatalogueResponseSerializer(serializers.Serializer):
models = ModelChoiceSerializer(
many=True,
help_text="Every model a run may use, newest catalogue from the LLM gateway. Empty when the gateway is unreachable.",
)
class RepositoryReadinessQuerySerializer(serializers.Serializer):
repository = serializers.CharField(required=True, help_text="Repository in org/repo format")
window_days = serializers.IntegerField(required=False, default=7, min_value=1, max_value=30)
refresh = serializers.BooleanField(required=False, default=False)
def validate_repository(self, value: str) -> str:
normalized = value.strip().lower()
parts = normalized.split("/")
if len(parts) != 2 or not parts[0] or not parts[1]:
raise serializers.ValidationError("Repository must be in the format organization/repository")
return normalized
class CapabilityStateSerializer(serializers.Serializer):
state = serializers.ChoiceField(
choices=["needs_setup", "detected", "waiting_for_data", "ready", "not_applicable", "unknown"],
help_text="Current state of the capability",
)
estimated = serializers.BooleanField(help_text="Whether the state is estimated from static analysis")
reason = serializers.CharField(help_text="Human-readable explanation")
evidence = serializers.DictField(required=False, default=dict, help_text="Supporting evidence")
class ScanEvidenceSerializer(serializers.Serializer):
filesScanned = serializers.IntegerField(help_text="Number of files scanned")
detectedFilesCount = serializers.IntegerField(help_text="Total candidate files detected")
eventNameCount = serializers.IntegerField(help_text="Number of distinct event names found")
foundPosthogInit = serializers.BooleanField(help_text="Whether posthog.init() was found in scanned files")
foundPosthogCapture = serializers.BooleanField(help_text="Whether posthog.capture() was found in scanned files")
foundErrorSignal = serializers.BooleanField(help_text="Whether error tracking signals were found in scanned files")
class RepositoryReadinessResponseSerializer(serializers.Serializer):
repository = serializers.CharField(help_text="Normalized repository identifier")
classification = serializers.CharField(help_text="Repository classification")
excluded = serializers.BooleanField(help_text="Whether the repository is excluded from readiness checks")
coreSuggestions = CapabilityStateSerializer(help_text="Tracking capability state")
replayInsights = CapabilityStateSerializer(help_text="Computer vision capability state")
errorInsights = CapabilityStateSerializer(help_text="Error tracking capability state")
overall = serializers.CharField(help_text="Overall readiness state")
evidenceTaskCount = serializers.IntegerField(help_text="Count of replay-derived evidence tasks")
windowDays = serializers.IntegerField(help_text="Lookback window in days")
generatedAt = serializers.CharField(help_text="ISO timestamp when the response was generated")
cacheAgeSeconds = serializers.IntegerField(help_text="Age of cached response in seconds")
scan = ScanEvidenceSerializer(required=False, help_text="Scan evidence details")
class ConnectionTokenResponseSerializer(serializers.Serializer):
"""Response containing a JWT token for direct sandbox connection"""
token = serializers.CharField(help_text="JWT token for authenticating with the sandbox")
class TaskRunLogsView(models.TextChoices):
FULL = "full", "full"
THREAD = "thread", "thread"
class TaskRunLogsQuerySerializer(serializers.Serializer):
"""Query parameters for reading part of a task run log"""
view = serializers.ChoiceField(
choices=TaskRunLogsView.choices,
default=TaskRunLogsView.FULL,
required=False,
help_text=(
"'full' returns every entry as stored. 'thread' drops the duplicate tool response copy in "
"_meta.claudeCode.toolResponse and keeps only its decisionReason and message, for clients that "
"render the conversation. It applies to the full log and to every slice."
),
)
tail_bytes = serializers.IntegerField(
required=False,
min_value=1,
help_text=(
"Return only the latest turns of the log: the shortest suffix that starts at a user turn and holds at "
"least this many bytes. The X-Log-Offset and X-Log-Count headers give the index of the first tail entry "
"and the size of the full log. The slice starts with X-Log-Preamble earlier entries that still set run "
"state, such as the run start, usage, mode, commands and open permission requests. X-Log-Turns-Before "
"counts the user turns before the slice, so a client numbers turns the way the full log does."
),
)
before = serializers.IntegerField(
required=False,
min_value=0,
help_text=(
"With tail_bytes, end the window before this entry index, so a client can page back through older "
"turns: pass the X-Log-Offset of the oldest page it holds."
),
)
start = serializers.IntegerField(
required=False,
min_value=0,
help_text=(
"With tail_bytes, return every entry from this index to the end, with no preamble, so a client that "
"holds the entries before it can catch up after a disconnect: pass the X-Log-Count of its last read. "
"When those entries are too large, the response holds the latest turns as tail_bytes alone returns "
"them, and X-Log-Offset is greater than start."
),
)
def validate(self, attrs: dict) -> dict:
for field in ("before", "start"):
if field in attrs and "tail_bytes" not in attrs:
raise serializers.ValidationError(f"Use {field} together with tail_bytes.")
if "before" in attrs and "start" in attrs:
raise serializers.ValidationError("Use before or start, not both.")
return attrs
class StreamReadTokenQuerySerializer(serializers.Serializer):
"""Query parameters for requesting a task run stream read token"""
resync = serializers.BooleanField(
required=False,
default=False,
help_text=(
"Set to true when the client can rebuild the run from its durable log after the agent-proxy "
"reports a trimmed stream cursor. Without it, runs that keep only a short live tail in Redis "
"are read from the Django endpoint, which replays the durable backlog itself."
),
)
class StreamReadTokenResponseSerializer(serializers.Serializer):
"""Response containing a JWT token (and resolved base URL) for reading a task run's live event stream"""
token = serializers.CharField(
help_text="Run-scoped JWT the browser presents to the agent-proxy to read this run's live event stream"
)
stream_base_url = serializers.CharField(
allow_null=True,
help_text=(
"Base URL of the agent-proxy to read the stream from when routing via the proxy is enabled for "
"this user. Null means read from the Django endpoint directly (same-origin). The client appends "
"the run's stream path and sends the token as a Bearer header when this is set."
),
)
MAX_IMPORTED_MCP_SERVERS = 20
MAX_IMPORTED_MCP_SERVER_NAME_LENGTH = 64
MAX_IMPORTED_MCP_HEADER_VALUE_LENGTH = 4096
MAX_IMPORTED_MCP_SERVERS_BYTES = 32768
# Names already taken by servers the sandbox always gets; imported entries must not shadow them.
RESERVED_IMPORTED_MCP_SERVER_NAMES = {"posthog"}
def _validate_unique_unreserved_mcp_names(value: list[dict]) -> None:
"""Reject reserved names and case-insensitive duplicates within an MCP-server list.
Shared by the imported and relayed validators; the per-field caps (count, payload size) stay
in each caller since they differ.
"""
seen: set[str] = set()
for server in value:
name = server["name"]
name_key = name.lower()
if name_key in RESERVED_IMPORTED_MCP_SERVER_NAMES:
raise serializers.ValidationError(f"'{name}' is a reserved MCP server name.")
if name_key in seen:
raise serializers.ValidationError(f"Duplicate MCP server name: '{name}'.")
seen.add(name_key)
class ImportedMcpServerHeaderSerializer(serializers.Serializer):
name = serializers.CharField(max_length=256)
value = serializers.CharField(
max_length=MAX_IMPORTED_MCP_HEADER_VALUE_LENGTH, allow_blank=True, trim_whitespace=False
)
class ImportedMcpServerListSerializer(serializers.ListSerializer):
def to_internal_value(self, data: object) -> list[dict[str, object]]:
if isinstance(data, list) and len(data) > MAX_IMPORTED_MCP_SERVERS:
raise serializers.ValidationError(f"At most {MAX_IMPORTED_MCP_SERVERS} imported MCP servers are allowed.")
return cast(list[dict[str, object]], super().to_internal_value(data))
class ImportedMcpServerSerializer(serializers.Serializer):
"""One client-imported MCP server, in the agent server's --mcpServers entry shape."""
type = serializers.ChoiceField(choices=["http", "sse"])
name = serializers.CharField(max_length=MAX_IMPORTED_MCP_SERVER_NAME_LENGTH)
url = serializers.URLField(max_length=2048)
headers = ImportedMcpServerHeaderSerializer(many=True, required=False, default=list)
class Meta:
list_serializer_class = ImportedMcpServerListSerializer
class ImportedMcpServersFieldMixin(serializers.Serializer):
"""Adds the write-only imported_mcp_servers field shared by both run-creation serializers."""
imported_mcp_servers = ImportedMcpServerSerializer(
many=True,
required=False,
allow_null=True,
default=None,
write_only=True,
help_text=(
"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."
),
)
def validate_imported_mcp_servers(self, value):
if not value:
return None
_validate_unique_unreserved_mcp_names(value)
if len(json.dumps(value)) > MAX_IMPORTED_MCP_SERVERS_BYTES:
raise serializers.ValidationError("Imported MCP servers payload is too large.")
resolved_ips_by_host = resolve_url_hosts_ips(server["url"] for server in value)
for server in value:
allowed, reason = is_url_allowed(server["url"], resolved_ips_by_host=resolved_ips_by_host)
if not allowed:
raise serializers.ValidationError(reason or "URL is not allowed.")
return value
MAX_RELAYED_MCP_SERVERS = 20
class RelayedMcpServerSerializer(serializers.Serializer):
"""One desktop-only MCP server relayed into the run — a name only, never configuration."""
name = serializers.CharField(max_length=MAX_IMPORTED_MCP_SERVER_NAME_LENGTH)
class RelayedMcpServersFieldMixin(serializers.Serializer):
"""Adds the write-only relayed_mcp_servers field shared by both run-creation serializers."""
relayed_mcp_servers = RelayedMcpServerSerializer(
many=True,
required=False,
allow_null=True,
default=None,
write_only=True,
help_text=(
"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."
),
)
def validate_relayed_mcp_servers(self, value):
if not value:
return None
if len(value) > MAX_RELAYED_MCP_SERVERS:
raise serializers.ValidationError(f"At most {MAX_RELAYED_MCP_SERVERS} relayed MCP servers are allowed.")
_validate_unique_unreserved_mcp_names(value)
return value
def get_relayed_imported_mcp_name_collision_error(attrs: dict) -> str | None:
"""Relayed and imported MCP server names must be disjoint (case-insensitively).
Both lists feed the same sandbox `mcpServers` namespace, so a shared name would make one
silently shadow the other. Cross-field, so it runs in each creation serializer's ``validate``.
"""
relayed = attrs.get("relayed_mcp_servers") or []
imported = attrs.get("imported_mcp_servers") or []
if not relayed or not imported:
return None
imported_names = {server["name"].lower() for server in imported}
for server in relayed:
if server["name"].lower() in imported_names:
return f"Relayed MCP server name '{server['name']}' collides with an imported MCP server name."
return None
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 whoever started the run; Desktop relays it interactively "
"and an API key caller relays it unattended. The token is sent in flight and never "
"stored on PostHog servers. Only PostHog Desktop and API keys can select "
"'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep "
"their billing choice and new runs use the PostHog gateway."
),
)
codex_model_access = serializers.ChoiceField(
choices=["posthog-gateway", "own-subscription"],
required=False,
allow_null=True,
default=None,
help_text=(
"How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a "
"ChatGPT access token from the PostHog API, refreshed from the ChatGPT account "
"the run owner connected in Desktop settings. If omitted or null, resumed runs keep their "
"billing choice and new runs use the PostHog gateway."
),
)
class TaskRunCreateRequestSerializer(
ImportedMcpServersFieldMixin, RelayedMcpServersFieldMixin, TaskRunPreferencesFieldMixin, TaskRunScheduleSerializer
):
"""Request body for creating a new task run"""
PR_AUTHORSHIP_MODE_CHOICES = [mode.value for mode in PrAuthorshipMode]
REASONING_EFFORT_CHOICES = list(REASONING_EFFORTS)
mode = serializers.ChoiceField(
choices=TaskExecutionMode.choices,
required=False,
default="background",
help_text="Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs",
)
branch = serializers.CharField(
required=False,
allow_null=True,
default=None,
max_length=255,
help_text="Git branch to checkout in the sandbox",
)
resume_from_run_id = serializers.UUIDField(
required=False,
default=None,
help_text="ID of a previous run to resume from. Must belong to the same task.",
)
pending_user_message = serializers.CharField(
required=False,
default=None,
allow_blank=True,
help_text="Initial or follow-up user message to include in the run prompt.",
)
pending_user_artifact_ids = serializers.ListField(
required=False,
default=list,
child=serializers.CharField(max_length=128),
help_text="Identifiers for staged task artifacts that should be attached to the initial run prompt.",
)
sandbox_environment_id = serializers.UUIDField(
required=False,
default=None,
help_text="Optional sandbox environment to apply for this cloud run.",
)
custom_image_id = serializers.UUIDField(
required=False,
default=None,
help_text="Optional custom base image for this cloud run's sandbox (Modal VM runtime only); "
"takes precedence over the environment's image.",
)
pr_authorship_mode = serializers.ChoiceField(
choices=PR_AUTHORSHIP_MODE_CHOICES,
required=False,
default=None,
help_text="Whether pull requests for this run should be authored by the user or the bot.",
)
auto_publish = serializers.BooleanField(
required=False,
allow_null=True,
default=None,
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."
),
)
run_source = serializers.ChoiceField(
choices=RunSource.choices,
required=False,
default=None,
help_text="High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.",
)
signal_report_id = serializers.CharField(
required=False,
default=None,
allow_blank=False,
help_text="Optional signal report identifier when this run was started from Inbox.",
)
runtime_adapter = serializers.ChoiceField(
choices=RuntimeAdapter.choices,
required=False,
default=None,
help_text="Agent runtime adapter to launch for this run. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime.",
)
model = serializers.CharField(
required=False,
default=None,
allow_blank=False,
help_text=(
"LLM model identifier. The server derives the runtime adapter when it is omitted. "
"A Pi task runs any listed model and takes no runtime adapter."
),
)
reasoning_effort = serializers.ChoiceField(
choices=REASONING_EFFORT_CHOICES,
required=False,
default=None,
help_text="Reasoning effort to request for models that expose an effort control.",
)
context_window = serializers.ChoiceField(
choices=CONTEXT_WINDOW_CHOICES,
required=False,
default=None,
help_text="Context window size for models that support the 1M window.",
)
fast_mode = serializers.BooleanField(
required=False,
allow_null=True,
default=None,
help_text="Enable fast mode for models that support it.",
)
github_user_token = serializers.CharField(
required=False,
default=None,
allow_blank=False,
write_only=True,
help_text=(
"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 = serializers.ChoiceField(
choices=ALL_INITIAL_PERMISSION_MODE_CHOICES,
required=False,
default=None,
help_text=(
"Initial permission mode for the agent session. Claude runtimes accept "
"'default', 'acceptEdits', 'plan', 'bypassPermissions', and 'auto'. "
"Codex runtimes accept 'plan', 'auto', 'read-only', and 'full-access'."
),
)
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 attrs.get("scheduled_at") is not None:
if is_pi_task or attrs.get("mode") != "background":
errors["scheduled_at"] = "Scheduling requires a background ACP run."
for field in ("github_user_token", "imported_mcp_servers", "relayed_mcp_servers"):
if attrs.get(field):
errors[field] = "Scheduled runs cannot use credentials or connections from a connected desktop."
if attrs.get("claude_model_access") == "own-subscription":
errors["claude_model_access"] = "Scheduled runs must use the PostHog gateway."
if attrs.get("model") and attrs.get("runtime_adapter") is None:
model_runtime_adapter = get_runtime_adapter_for_model(attrs["model"]) or next(
(
RuntimeAdapter(choice.runtime_adapter)
for choice in available_model_choices(TASK_RUN_GATEWAY_PRODUCT)
if choice.model == attrs["model"]
),
None,
)
if model_runtime_adapter is None:
errors["model"] = "Unknown model. Use tasks-models-retrieve to list available models."
elif not is_pi_task:
attrs["runtime_adapter"] = model_runtime_adapter
if is_pi_task:
errors.update(_pi_task_run_request_errors(attrs))
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")
runtime_adapter = attrs.get("runtime_adapter")
if permission_mode_error := get_initial_permission_mode_error(initial_permission_mode, runtime_adapter):
errors["initial_permission_mode"] = permission_mode_error
pending_user_message = attrs.get("pending_user_message")
pending_user_artifact_ids = attrs.get("pending_user_artifact_ids") or []
if pending_user_message is not None:
trimmed_message = pending_user_message.strip()
attrs["pending_user_message"] = trimmed_message or None
if not attrs.get("pending_user_message") and not pending_user_artifact_ids:
attrs.pop("pending_user_message", None)
if is_pi_task:
if "model" not in errors and (
model_access_error := get_model_access_error(
attrs.get("model"), distinct_id=request_distinct_id(self.context)
)
):
errors["model"] = model_access_error
if errors:
raise serializers.ValidationError(errors)
return attrs
runtime_fields = ("runtime_adapter", "model")
has_runtime_selection = any(
attrs.get(field) is not None
for field in (*runtime_fields, "reasoning_effort", "context_window", "fast_mode")
)
if not has_runtime_selection:
if errors:
raise serializers.ValidationError(errors)
return attrs
for field in runtime_fields:
if attrs.get(field) is None:
errors[field] = "This field is required when selecting a cloud runtime."
reasoning_effort_error = get_reasoning_effort_error(
runtime_adapter=attrs.get("runtime_adapter"),
model=attrs.get("model"),
reasoning_effort=attrs.get("reasoning_effort"),
)
if reasoning_effort_error is not None:
errors["reasoning_effort"] = reasoning_effort_error
_capture_rejected_reasoning_effort(
self.context,
runtime_adapter=attrs.get("runtime_adapter"),
model=attrs.get("model"),
reasoning_effort=attrs.get("reasoning_effort"),
error=reasoning_effort_error,
)
model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))
if model_access_error is not None:
errors["model"] = model_access_error
if errors:
raise serializers.ValidationError(errors)
return attrs
class TaskRunBootstrapCreateRequestSerializer(
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 if source != RunSource.AGENT]
REASONING_EFFORT_CHOICES = TASK_RUN_REASONING_EFFORT_CHOICES
environment = serializers.ChoiceField(
choices=[environment.value for environment in tasks_facade.TaskRunEnvironment],
required=False,
default=tasks_facade.TaskRunEnvironment.LOCAL,
help_text="Execution environment for the new run. Use 'cloud' for remote sandbox runs and 'local' for desktop sessions.",
)
mode = serializers.ChoiceField(
choices=TaskExecutionMode.choices,
required=False,
default="background",
help_text="Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs",
)
branch = serializers.CharField(
required=False,
allow_null=True,
default=None,
max_length=255,
help_text="Git branch to checkout in the sandbox",
)
sandbox_environment_id = serializers.UUIDField(
required=False,
default=None,
help_text="Optional sandbox environment to apply for this cloud run.",
)
custom_image_id = serializers.UUIDField(
required=False,
default=None,
help_text="Optional custom base image for this cloud run's sandbox (Modal VM runtime only); "
"takes precedence over the environment's image.",
)
pr_authorship_mode = serializers.ChoiceField(
choices=PR_AUTHORSHIP_MODE_CHOICES,
required=False,
default=None,
help_text="Whether pull requests for this run should be authored by the user or the bot.",
)
auto_publish = serializers.BooleanField(
required=False,
allow_null=True,
default=None,
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."
),
)
run_source = serializers.ChoiceField(
choices=RUN_SOURCE_CHOICES,
required=False,
default=None,
help_text="High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.",
)
signal_report_id = serializers.CharField(
required=False,
default=None,
allow_blank=False,
help_text="Optional signal report identifier when this run was started from Inbox.",
)
runtime_adapter = serializers.ChoiceField(
choices=RuntimeAdapter.choices,
required=False,
default=None,
help_text="Agent runtime adapter to launch for this run. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime.",
)
model = serializers.CharField(
required=False,
default=None,
allow_blank=False,
help_text="LLM model identifier to run in the selected runtime.",
)
reasoning_effort = serializers.ChoiceField(
choices=REASONING_EFFORT_CHOICES,
required=False,
default=None,
help_text="Reasoning effort to request for models that expose an effort control.",
)
context_window = serializers.ChoiceField(
choices=CONTEXT_WINDOW_CHOICES,
required=False,
default=None,
help_text="Context window size for models that support the 1M window.",
)
fast_mode = serializers.BooleanField(
required=False,
allow_null=True,
default=None,
help_text="Enable fast mode for models that support it.",
)
github_user_token = serializers.CharField(
required=False,
default=None,
allow_blank=False,
write_only=True,
help_text="Ephemeral GitHub user token from PostHog Desktop for user-authored cloud pull requests.",
)
initial_permission_mode = serializers.ChoiceField(
choices=ALL_INITIAL_PERMISSION_MODE_CHOICES,
required=False,
default=None,
help_text=(
"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'."
),
)
def validate(self, attrs):
_validate_subscription_caller(attrs, self.context)
errors: dict[str, str] = {}
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")
runtime_adapter = attrs.get("runtime_adapter")
if _is_pi_task_run_request(self.context):
errors.update(_pi_task_run_request_errors(attrs))
if errors:
raise serializers.ValidationError(errors)
return attrs
if permission_mode_error := get_initial_permission_mode_error(initial_permission_mode, runtime_adapter):
errors["initial_permission_mode"] = permission_mode_error
runtime_fields = ("runtime_adapter", "model")
has_runtime_selection = any(
attrs.get(field) is not None
for field in (*runtime_fields, "reasoning_effort", "context_window", "fast_mode")
)
if not has_runtime_selection:
if errors:
raise serializers.ValidationError(errors)
return attrs
for field in runtime_fields:
if attrs.get(field) is None:
errors[field] = "This field is required when selecting a cloud runtime."
reasoning_effort_error = get_reasoning_effort_error(
runtime_adapter=attrs.get("runtime_adapter"),
model=attrs.get("model"),
reasoning_effort=attrs.get("reasoning_effort"),
)
if reasoning_effort_error is not None:
errors["reasoning_effort"] = reasoning_effort_error
_capture_rejected_reasoning_effort(
self.context,
runtime_adapter=attrs.get("runtime_adapter"),
model=attrs.get("model"),
reasoning_effort=attrs.get("reasoning_effort"),
error=reasoning_effort_error,
)
model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))
if model_access_error is not None:
errors["model"] = model_access_error
if errors:
raise serializers.ValidationError(errors)
return attrs
class WarmTaskRequestSerializer(serializers.Serializer):
"""Request body for warming a full idling Run while composing a Code-app cloud task.
Collection-level: no task exists yet at typing time. The warmer births a draft Task and an
interactive Run that boots and starts the agent, optionally cloning and checking out a repository,
then idles awaiting the first message. `github_integration` is a plain integration PK (an integer);
the view re-scopes it to the caller's team before use.
"""
repository = serializers.CharField(
required=False,
default=None,
allow_null=True,
max_length=255,
help_text="Optional GitHub repository to clone, in `organization/repo` format (e.g. `posthog/posthog`).",
)
repositories = serializers.ListField(
child=serializers.CharField(max_length=255),
required=False,
max_length=3,
help_text="GitHub repositories to clone into the warm sandbox, each in `organization/repo` format.",
)
def validate_repositories(self, value: list[str]) -> list[str]:
return TaskWriteSerializer().validate_repositories(value)
github_integration = serializers.IntegerField(
required=False,
default=None,
allow_null=True,
help_text=(
"Primary key of the team's GitHub integration. Required when a repository is selected (it is "
"what the sandbox clones with). Accepted without a repository too: the warm Run then boots "
"with that integration's GitHub credentials, matching a repo-less create that carries it."
),
)
branch = serializers.CharField(
required=False,
default=None,
allow_blank=True,
allow_null=True,
max_length=255,
help_text="Branch to check out in the warm sandbox. Defaults to the repository's default branch when omitted.",
)
runtime_adapter = serializers.ChoiceField(
choices=RuntimeAdapter.choices,
required=False,
default=None,
allow_null=True,
help_text=(
"Agent runtime adapter to warm the sandbox on ('claude' or 'codex'). The warm Run starts the "
"agent on this runtime so a matching submit reuses it; a submit selecting a different runtime "
"falls through to a cold Run instead of reusing a mismatched warm session."
),
)
model = serializers.CharField(
required=False,
default=None,
allow_blank=False,
allow_null=True,
help_text="LLM model identifier to warm the sandbox on. A submit selecting a different model won't reuse this warm Run.",
)
reasoning_effort = serializers.ChoiceField(
choices=list(REASONING_EFFORTS),
required=False,
default=None,
allow_null=True,
help_text="Reasoning effort to warm the sandbox on for models that expose an effort control.",
)
sandbox_environment_id = serializers.UUIDField(
required=False,
default=None,
allow_null=True,
help_text="Optional sandbox environment to provision before the task is submitted.",
)
custom_image_id = serializers.UUIDField(
required=False,
default=None,
allow_null=True,
help_text="Optional custom base image to provision before the task is submitted; takes precedence over the environment's image.",
)
origin_product = serializers.ChoiceField(
choices=WARMABLE_ORIGIN_PRODUCTS,
required=False,
default=tasks_facade.TaskOriginProduct.USER_CREATED,
help_text=(
"Product the warm Run is for. Fixed when the sandbox boots — it selects the OAuth app, the "
"quota gate, the warm-pool budget, and PR authorship — so a submit only reuses a warm born "
"under the same origin. Defaults to the Code app."
),
)
initial_permission_mode = serializers.ChoiceField(
choices=ALL_INITIAL_PERMISSION_MODE_CHOICES,
required=False,
default=None,
allow_null=True,
help_text=(
"Permission mode to boot the agent session on. Read at session construction, so it cannot be "
"changed once the sandbox is warm — a submit selecting a different mode falls through to a "
"cold Run. Omit to take the runtime's default."
),
)
signal_report = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
queryset=UserIntegration.objects.none(), # placeholder, replaced in __init__
required=False,
default=None,
allow_null=True,
help_text=(
"Inbox report the warm discussion is about. Required with origin_product `signal_report`, where the "
"warm Run boots repo-less and the submit that creates the report's discussion task activates it."
),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
signal_report_field = cast(serializers.PrimaryKeyRelatedField, self.fields["signal_report"])
signal_report_field.queryset = tasks_facade.signal_report_queryset() # type: ignore[arg-type] # DRF stubs type queryset as a Manager, which django-stubs treats as a descriptor
def validate_repository(self, value: str | None) -> str | None:
if value is None:
return None
normalized = value.strip().lower()
parts = normalized.split("/")
if len(parts) != 2 or not parts[0] or not parts[1]:
raise serializers.ValidationError("Repository must be in the format organization/repository")
return normalized
def validate_signal_report(self, value):
if value and value.team_id != self.context["team"].id:
raise serializers.ValidationError("Signal report must belong to the same team")
return value
def validate(self, attrs):
if attrs.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT:
if not attrs.get("signal_report"):
raise serializers.ValidationError({"signal_report": "Requires signal_report when set."})
if attrs.get("repository") or attrs.get("repositories") or attrs.get("github_integration"):
raise serializers.ValidationError(
{"repository": "Signal report tasks resolve their repository server-side."}
)
elif attrs.get("signal_report"):
raise serializers.ValidationError({"signal_report": "Requires origin_product signal_report when set."})
# A repository needs an integration to clone with. The reverse is allowed: the create path
# accepts and stores an integration on a repo-less task, and the sandbox uses it to mint a
# GitHub token, so a repo-less warm must carry the same integration to boot with the same
# credentials and to match that create on reuse.
if attrs.get("repository") and not attrs.get("github_integration"):
raise serializers.ValidationError("GitHub integration is required when a repository is provided.")
# Warming starts the agent on this model, so it bills like a run and gates like one.
model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))
if model_access_error is not None:
raise serializers.ValidationError({"model": model_access_error})
# The agent session is built with this mode at boot and cannot be changed once warm, so a pair
# the run request would reject must not reach a sandbox here either.
permission_mode_error = get_initial_permission_mode_error(
attrs.get("initial_permission_mode"), attrs.get("runtime_adapter")
)
if permission_mode_error is not None:
raise serializers.ValidationError({"initial_permission_mode": permission_mode_error})
return attrs
class WarmTaskResponseSerializer(serializers.Serializer):
"""Response for a successful warm request — the draft Task + idling warm Run reused on submit."""
task_id = serializers.UUIDField(
help_text="Id of the draft Task birthed for the warm Run.",
)
run_id = serializers.UUIDField(
help_text="Id of the idling warm Run. The normal create+run path reuses and activates it on submit.",
)
class WarmTaskResumeRequestSerializer(serializers.Serializer):
"""Request body for warming a successor to an existing terminal task run."""
resume_from_run_id = serializers.UUIDField(
help_text="ID of the task's latest terminal run whose snapshot and conversation should be resumed.",
)
runtime_adapter = serializers.ChoiceField(
choices=RuntimeAdapter.choices,
required=False,
default=None,
help_text="Agent runtime adapter to start before the next message is submitted.",
)
model = serializers.CharField(
required=False,
default=None,
allow_blank=False,
help_text="LLM model to start before the next message is submitted.",
)
reasoning_effort = serializers.ChoiceField(
choices=list(REASONING_EFFORTS),
required=False,
default=None,
help_text="Reasoning effort to apply when the warmed successor receives its first message.",
)
initial_permission_mode = serializers.ChoiceField(
choices=ALL_INITIAL_PERMISSION_MODE_CHOICES,
required=False,
default=None,
help_text="Initial permission mode for the warmed successor's agent session.",
)
def validate(self, attrs):
errors: dict[str, str] = {}
runtime_adapter = attrs.get("runtime_adapter")
model = attrs.get("model")
if (runtime_adapter is None) != (model is None):
missing_field = "runtime_adapter" if runtime_adapter is None else "model"
errors[missing_field] = "This field is required when selecting a cloud runtime."
initial_permission_mode = attrs.get("initial_permission_mode")
if initial_permission_mode is not None:
if runtime_adapter is None:
errors["initial_permission_mode"] = "This field requires runtime_adapter to be set."
else:
allowed_permission_modes = (
list(CODEX_INITIAL_PERMISSION_MODE_CHOICES)
if runtime_adapter == RuntimeAdapter.CODEX.value
else list(INITIAL_PERMISSION_MODE_CHOICES)
)
if initial_permission_mode not in allowed_permission_modes:
allowed_values = ", ".join(f"'{value}'" for value in allowed_permission_modes)
errors["initial_permission_mode"] = (
f"Invalid choice '{initial_permission_mode}' for runtime_adapter "
f"'{runtime_adapter}'. Supported values: {allowed_values}."
)
reasoning_effort_error = get_reasoning_effort_error(
runtime_adapter=runtime_adapter,
model=model,
reasoning_effort=attrs.get("reasoning_effort"),
)
if reasoning_effort_error is not None:
errors["reasoning_effort"] = reasoning_effort_error
_capture_rejected_reasoning_effort(
self.context,
runtime_adapter=runtime_adapter,
model=model,
reasoning_effort=attrs.get("reasoning_effort"),
error=reasoning_effort_error,
)
model_access_error = get_model_access_error(model, distinct_id=request_distinct_id(self.context))
if model_access_error is not None:
errors["model"] = model_access_error
if errors:
raise serializers.ValidationError(errors)
return attrs
class WarmTaskResumeResponseSerializer(serializers.Serializer):
"""Response for a successfully warmed successor run on an existing task."""
task_id = serializers.UUIDField(help_text="ID of the existing task being resumed.")
run_id = serializers.UUIDField(help_text="ID of the idling successor run that submit will activate.")
class TaskRunStartRequestSerializer(serializers.Serializer):
pending_user_message = serializers.CharField(
required=False,
default=None,
allow_blank=True,
help_text="Initial or follow-up user message to include in the run prompt.",
)
pending_user_artifact_ids = serializers.ListField(
required=False,
default=list,
child=serializers.CharField(max_length=128),
help_text="Identifiers for run artifacts that should be attached to the next user message delivered to the sandbox.",
)
def validate(self, attrs):
pending_user_message = attrs.get("pending_user_message")
if pending_user_message is not None:
trimmed_message = pending_user_message.strip()
attrs["pending_user_message"] = trimmed_message or None
return attrs
class TaskRunCancelRequestSerializer(serializers.Serializer):
reason = serializers.CharField(
required=False,
default=None,
allow_blank=True,
allow_null=True,
max_length=500,
help_text="Optional reason for the cancellation, recorded on the run and shown to run watchers.",
)
only_if_awaiting_first_message = serializers.BooleanField(
required=False,
default=False,
help_text=(
"Cancel only while the run is still a warm sandbox awaiting its first message. A run that "
"has since received one is left alone and returned unchanged. Set this when handing a warm "
"sandbox back, so a release that races a submit cannot stop the run that submit started."
),
)
class ClaudeTaskRunCreateSchemaSerializer(TaskRunCreateRequestSerializer):
runtime_adapter = serializers.ChoiceField(
choices=[RuntimeAdapter.CLAUDE.value],
required=True,
help_text="Agent runtime adapter to launch for this run. Must be 'claude' for Claude runtimes.",
)
model = serializers.CharField(
required=True,
allow_blank=False,
help_text="LLM model identifier to run in the Claude runtime.",
)
initial_permission_mode = serializers.ChoiceField(
choices=INITIAL_PERMISSION_MODE_CHOICES,
required=False,
default=None,
help_text="Initial permission mode for Claude runtimes.",
)
class CodexTaskRunCreateSchemaSerializer(TaskRunCreateRequestSerializer):
runtime_adapter = serializers.ChoiceField(
choices=[RuntimeAdapter.CODEX.value],
required=True,
help_text="Agent runtime adapter to launch for this run. Must be 'codex' for Codex runtimes.",
)
model = serializers.CharField(
required=True,
allow_blank=False,
help_text="LLM model identifier to run in the Codex runtime.",
)
initial_permission_mode = serializers.ChoiceField(
choices=CODEX_INITIAL_PERMISSION_MODE_CHOICES,
required=False,
default=None,
help_text="Initial permission mode for Codex runtimes.",
)
class TaskRunResumeRequestSchemaSerializer(TaskRunScheduleSerializer):
model = serializers.CharField(required=False, allow_blank=False)
reasoning_effort = serializers.ChoiceField(
choices=TaskRunCreateRequestSerializer.REASONING_EFFORT_CHOICES, required=False
)
mode = serializers.ChoiceField(
choices=TaskExecutionMode.choices,
required=False,
default="background",
help_text="Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs",
)
branch = serializers.CharField(
required=False,
allow_null=True,
default=None,
max_length=255,
help_text="Git branch to checkout in the sandbox",
)
resume_from_run_id = serializers.UUIDField(
required=False,
default=None,
help_text="ID of a previous run to resume from. Must belong to the same task.",
)
pending_user_message = serializers.CharField(
required=False,
default=None,
allow_blank=False,
help_text="Initial or follow-up user message to include in the run prompt.",
)
sandbox_environment_id = serializers.UUIDField(
required=False,
default=None,
help_text="Optional sandbox environment to apply for this cloud run.",
)
custom_image_id = serializers.UUIDField(
required=False,
default=None,
help_text="Optional custom base image for this cloud run's sandbox (Modal VM runtime only); "
"takes precedence over the environment's image.",
)
pr_authorship_mode = serializers.ChoiceField(
choices=TaskRunCreateRequestSerializer.PR_AUTHORSHIP_MODE_CHOICES,
required=False,
default=None,
help_text="Whether pull requests for this run should be authored by the user or the bot.",
)
run_source = serializers.ChoiceField(
choices=RunSource.choices,
required=False,
default=None,
help_text="High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.",
)
signal_report_id = serializers.CharField(
required=False,
default=None,
allow_blank=False,
help_text="Optional signal report identifier when this run was started from Inbox.",
)
github_user_token = serializers.CharField(
required=False,
default=None,
allow_blank=False,
write_only=True,
help_text=(
"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."
),
)
TaskRunCreateRequestSchemaSerializer = PolymorphicProxySerializer(
component_name="TaskRunCreateRequestSchema",
serializers=[
ClaudeTaskRunCreateSchemaSerializer,
CodexTaskRunCreateSchemaSerializer,
TaskRunResumeRequestSchemaSerializer,
],
resource_type_field_name=None,
)
class TaskRunCommandRequestSerializer(serializers.Serializer):
"""JSON-RPC request to send a command to the agent server in the sandbox."""
ALLOWED_METHODS = [
"user_message",
"cancel",
"close",
"permission_response",
"set_config_option",
"mcp_response",
"credential_response",
"pi/rpc",
"queue_get",
"queue_clear",
"side_question",
]
# Cap on the serialized mcp_response params (docs/CLOUD-MCP-RELAY.md): the relayed JSON-RPC
# response payload plus envelope must fit in 300 KB. Params are forwarded to the sandbox
# verbatim and never persisted or captured — they carry data from the user's private systems.
MAX_MCP_RESPONSE_PARAMS_BYTES = 300_000
# A side question is forwarded into an agent turn, so its length is the direct lever on
# model spend. Generous for a one-shot question, far under the request body cap.
MAX_SIDE_QUESTION_CHARS = 10_000
jsonrpc = serializers.ChoiceField(
choices=["2.0"],
help_text="JSON-RPC version, must be '2.0'",
)
method = serializers.ChoiceField(
choices=ALLOWED_METHODS,
help_text="Command method to execute on the agent server",
)
params = serializers.DictField(
required=False,
default=dict,
help_text="Parameters for the command",
)
id = serializers.JSONField(
required=False,
default=None,
help_text="Optional JSON-RPC request ID (string or number)",
)
def validate_id(self, value):
if value is not None and not isinstance(value, str | int | float):
raise serializers.ValidationError("id must be a string or number")
return value
@staticmethod
def _require_nonempty_string(params: dict, key: str) -> None:
value = params.get(key)
if not value or not isinstance(value, str) or not value.strip():
raise serializers.ValidationError({"params": f"{key} is required and must be a non-empty string"})
def validate(self, attrs):
method = attrs["method"]
params = attrs.get("params", {})
if method == "user_message":
content = params.get("content")
artifact_ids = params.get("artifact_ids")
steer = params.get("steer")
if steer is not None and not isinstance(steer, bool):
raise serializers.ValidationError({"params": "steer must be a boolean when provided"})
normalized_content = None
if content is not None:
if not isinstance(content, str):
raise serializers.ValidationError({"params": "content must be a string when provided"})
normalized_content = content.strip()
if normalized_content:
params["content"] = normalized_content
else:
params.pop("content", None)
if artifact_ids is None:
normalized_artifact_ids: list[str] = []
elif not isinstance(artifact_ids, list) or not all(
isinstance(value, str) and value.strip() for value in artifact_ids
):
raise serializers.ValidationError({"params": "artifact_ids must be a list of non-empty strings"})
else:
normalized_artifact_ids = [value.strip() for value in artifact_ids]
params["artifact_ids"] = normalized_artifact_ids
if not normalized_content and not normalized_artifact_ids:
raise serializers.ValidationError(
{"params": "user_message requires a non-empty content string, artifact_ids, or both"}
)
elif method == "side_question":
self._require_nonempty_string(params, "question")
question = params["question"].strip()
if len(question) > self.MAX_SIDE_QUESTION_CHARS:
raise serializers.ValidationError(
{"params": f"question must be at most {self.MAX_SIDE_QUESTION_CHARS} characters"}
)
params["question"] = question
elif method == "pi/rpc":
command = params.get("command")
if not isinstance(command, dict):
raise serializers.ValidationError({"params": "command must be an object"})
command_type = command.get("type")
if not isinstance(command_type, str) or not command_type:
raise serializers.ValidationError({"params": "command.type must be a non-empty string"})
command_id = command.get("id")
if not isinstance(command_id, str) or not command_id:
raise serializers.ValidationError({"params": "command.id must be a non-empty string"})
if attrs.get("id") != command_id:
raise serializers.ValidationError({"id": "id must match params.command.id"})
elif method == "permission_response":
self._require_nonempty_string(params, "requestId")
self._require_nonempty_string(params, "optionId")
elif method == "set_config_option":
self._require_nonempty_string(params, "configId")
self._require_nonempty_string(params, "value")
elif method == "mcp_response":
self._require_nonempty_string(params, "requestId")
self._require_nonempty_string(params, "server")
payload = params.get("payload")
error = params.get("error")
if (payload is None) == (error is None):
raise serializers.ValidationError({"params": "mcp_response requires exactly one of payload or error"})
if payload is not None and not isinstance(payload, dict):
raise serializers.ValidationError({"params": "payload must be an object"})
if error is not None and (
not isinstance(error, dict)
or isinstance(error.get("code"), bool)
or not isinstance(error.get("code"), int)
or not isinstance(error.get("message"), str)
):
raise serializers.ValidationError(
{"params": "error must be an object with an integer code and a string message"}
)
if len(json.dumps(params)) > self.MAX_MCP_RESPONSE_PARAMS_BYTES:
raise serializers.ValidationError({"params": "mcp_response params exceed the 300 KB limit"})
elif method == "credential_response":
self._require_nonempty_string(params, "requestId")
if len(params["requestId"]) > 128:
raise serializers.ValidationError({"params": "requestId exceeds the 128 character limit"})
if params.get("credential") != "claude_subscription_token":
raise serializers.ValidationError({"params": "Unsupported credential"})
token = params.get("token")
error = params.get("error")
if (token is None) == (error is None):
raise serializers.ValidationError(
{"params": "credential_response requires exactly one of token or error"}
)
if token is not None and (not isinstance(token, str) or not token.strip() or len(token) > 4096):
raise serializers.ValidationError({"params": "token must contain between 1 and 4096 characters"})
if error is not None and error not in ("no_token", "store_unavailable"):
raise serializers.ValidationError({"params": "Unsupported credential error"})
return attrs
class TaskRunCommandResponseSerializer(serializers.Serializer):
"""Response from the agent server command endpoint."""
jsonrpc = serializers.CharField(help_text="JSON-RPC version")
id = serializers.JSONField(required=False, default=None, help_text="Request ID echoed back (string or number)")
result = serializers.JSONField(
required=False, help_text="Command result. Permission responses confirm acceptance only with resolved=true."
)
error = serializers.DictField(
required=False, help_text="JSON-RPC error details, including failures returned with HTTP 200"
)
class TaskRunSessionLogsQuerySerializer(serializers.Serializer):
"""Query parameters for filtering task run log events"""
after = serializers.DateTimeField(
required=False,
help_text="Only return events after this ISO8601 timestamp",
)
event_types = serializers.CharField(
required=False,
help_text="Comma-separated list of event types to include",
)
exclude_types = serializers.CharField(
required=False,
help_text="Comma-separated list of event types to exclude",
)
limit = serializers.IntegerField(
required=False,
default=1000,
min_value=1,
max_value=5000,
help_text="Maximum number of entries to return (default 1000, max 5000)",
)
offset = serializers.IntegerField(
required=False,
default=0,
min_value=0,
help_text="Zero-based offset into the filtered log entries",
)
# One serializer for every read. The list used to carry a subset, and because the settings
# page edits an environment straight off the list, each field missing there read as unset
# rather than as unfetched: a saved variable set looked empty. Both also generated the same
# OpenAPI component, so the narrower one is what downstream clients were typed against.
class SandboxEnvironmentSerializer(DataclassSerializer):
"""A sandbox environment, as returned by list, detail, create and update."""
created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
class Meta:
dataclass = SandboxEnvironmentDTO
fields = [
"id",
"name",
"network_access_level",
"allowed_domains",
"include_default_domains",
"repositories",
"has_environment_variables",
"environment_variable_keys",
"private",
"internal",
"effective_domains",
"created_by",
"created_at",
"updated_at",
"custom_image_id",
"custom_image_name",
"custom_image_status",
]
extra_kwargs = {
"has_environment_variables": {
"help_text": "Whether any environment variables are set on this environment."
},
"environment_variable_keys": {
"help_text": (
"Names of the environment variables that are set, sorted. Values are write-only and never returned."
)
},
}
class SandboxEnvironmentWriteSerializer(serializers.Serializer):
"""Request body for creating or updating a sandbox environment."""
name = serializers.CharField(max_length=255, help_text="Display name for the environment.")
network_access_level = serializers.ChoiceField(
choices=tasks_facade.SandboxNetworkAccessLevel.choices,
required=False,
default=tasks_facade.SandboxNetworkAccessLevel.FULL,
help_text="Network access policy: trusted (default allowlist), full (unrestricted), or custom.",
)
allowed_domains = serializers.ListField(
child=serializers.CharField(max_length=255),
required=False,
default=list,
max_length=tasks_facade.MAX_SANDBOX_ALLOWED_DOMAINS,
error_messages={"max_length": f"You can allow up to {tasks_facade.MAX_SANDBOX_ALLOWED_DOMAINS} domains."},
help_text="Allowed domains for custom network access.",
)
include_default_domains = serializers.BooleanField(
required=False,
default=False,
help_text="Whether to include default trusted domains (GitHub, npm, PyPI).",
)
repositories = serializers.ListField(
child=serializers.CharField(max_length=255),
required=False,
default=list,
help_text="Repositories this environment applies to (format: org/repo).",
)
environment_variables = serializers.JSONField(
write_only=True,
required=False,
default=dict,
help_text="Encrypted environment variables (write-only, never returned in responses).",
)
private = serializers.BooleanField(
required=False,
default=True,
help_text="If true, only the creator can see this environment; otherwise the whole team can.",
)
custom_image_id = serializers.UUIDField(
required=False,
allow_null=True,
help_text="Custom base image for this environment's sandboxes (Modal VM runtime only); null uses the default base.",
)
def validate_environment_variables(self, value):
if value:
for key in value:
if not tasks_facade.is_valid_sandbox_env_var_key(key):
raise serializers.ValidationError(
f"Invalid environment variable key: {key!r}. Must match [A-Za-z_][A-Za-z0-9_]*"
)
if tasks_facade.is_blocked_sandbox_env_var_key(key):
raise serializers.ValidationError(
f"Environment variable key {key!r} is not allowed: it can change how sandbox "
"processes execute code (e.g. NODE_OPTIONS, LD_PRELOAD)."
)
if tasks_facade.is_reserved_sandbox_env_var_key(key):
raise serializers.ValidationError(
f"Environment variable key {key!r} is reserved and managed by PostHog; it cannot be set."
)
return value
def validate_allowed_domains(self, value: list[str]) -> list[str]:
try:
return tasks_facade.normalize_sandbox_allowed_domains(value)
except ValueError as error:
raise serializers.ValidationError(
f"{error}. Enter domain names such as example.com or *.example.com without a scheme, path, or port."
) from error
class SandboxCustomImageSerializer(DataclassSerializer):
"""Detail response for a custom sandbox base image."""
created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
class Meta:
dataclass = SandboxCustomImageDTO
fields = [
"id",
"name",
"description",
"repository",
"private",
"status",
"version",
"modal_image_name",
"spec",
"spec_yaml",
"scan_result",
"build_log",
"error",
"builder_task_id",
"created_by",
"created_at",
"updated_at",
]
class SandboxCustomImageWriteSerializer(serializers.Serializer):
"""Request body for creating a custom sandbox base image."""
name = serializers.CharField(max_length=255, help_text="Display name for the custom image.")
description = serializers.CharField(
required=False,
allow_blank=True,
default="",
help_text="What should go into the image; seeds the image-builder agent conversation.",
)
repository = serializers.CharField(
required=False,
allow_null=True,
default=None,
max_length=255,
help_text="Optional 'org/repo' the builder session clones so it can verify the image "
"brings up that repository's dependencies.",
)
private = serializers.BooleanField(
required=False,
default=False,
help_text="If true, only you can see and use this image; otherwise the whole team can.",
)
class SandboxCustomImageBuildSerializer(serializers.Serializer):
"""Request body for scanning and building a custom sandbox base image."""
spec_yaml = serializers.CharField(
required=False,
allow_null=True,
default=None,
help_text="Image spec YAML to build. When omitted, the spec is read from the builder agent's live sandbox.",
)
class SandboxCustomImageUpdateSerializer(serializers.Serializer):
"""Request body for renaming / re-describing a custom sandbox base image."""
name = serializers.CharField(
required=False,
min_length=1,
max_length=255,
help_text="New display name for the custom image. Omit to leave unchanged.",
)
description = serializers.CharField(
required=False,
allow_blank=True,
help_text="New description. Omit to leave unchanged; pass an empty string to clear it.",
)
def validate_name(self, value: str) -> str:
if value is not None and not value.strip():
raise serializers.ValidationError("Name cannot be blank.")
return value
class TaskPresenceBeaconRequestSerializer(serializers.Serializer):
"""Request body for the presence beacon and beacon-leave endpoints.
`device_id` is the UUID of the caller's `UserPushToken` row, which the
client received when it registered for push via `/api/users/@me/push_tokens/`.
The client is expected to use the same identifier on the beacon and leave
calls; if the user has unregistered the underlying push token, the value
won't resolve and the call returns 404 — at which point pushes were
already not going there anyway.
"""
device_id = serializers.UUIDField(
help_text="UUID of the caller's UserPushToken (returned by `/api/users/@me/push_tokens/` on register).",
)
class SlackThreadContextQuerySerializer(serializers.Serializer):
"""Query params for the slack-thread debug endpoint."""
url = serializers.URLField(
help_text=(
"Full Slack permalink to any message in the thread (e.g. "
"https://posthog.slack.com/archives/C…/p1779956938619299). Replies inside the "
"thread are accepted too — the `thread_ts` query param (when present) takes "
"precedence over the in-path message ts."
),
)
class SlackThreadContextThreadSerializer(serializers.Serializer):
"""Slack-side identifiers and the mapping metadata for a thread → task lookup."""
url = serializers.CharField(help_text="Echoed input URL.")
channel = serializers.CharField(help_text="Slack channel id parsed from the URL (e.g. C0ACRAMJUAG).")
thread_ts = serializers.CharField(help_text="Slack thread_ts (e.g. 1779956938.619299).")
slack_workspace_id = serializers.CharField(
allow_null=True,
help_text="Slack workspace id (e.g. T…). Null when no mapping exists yet.",
)
mentioning_slack_user_id = serializers.CharField(
allow_null=True,
help_text="The Slack user who triggered the task. Null when no mapping exists yet.",
)
queue_workflow_id = serializers.CharField(
allow_null=True,
help_text=(
"Temporal workflow id of the per-conversation mention queue "
"(`slack-app-mention-<workspace>:<channel>:<thread_ts>`) that serializes the thread's "
"messages before any run exists. Null when the workspace id cannot be resolved."
),
)
queue_workflow_url = serializers.CharField(
allow_null=True,
help_text="Full Temporal Web UI URL for the mention queue workflow; null when `TEMPORAL_UI_HOST` is unset.",
)
mapping_admin_url = serializers.CharField(
allow_null=True,
help_text="Absolute URL to the SlackThreadTaskMapping row in Django admin. Null when no mapping exists.",
)
class SlackThreadContextTaskSerializer(serializers.Serializer):
"""The PostHog Task linked to the Slack thread."""
id = serializers.CharField(help_text="UUID of the Task row.")
team_id = serializers.IntegerField(help_text="Team that owns the task.")
title = serializers.CharField(help_text="Task title (typically the first ~255 chars of the Slack ask).")
repository = serializers.CharField(
allow_null=True,
help_text="Resolved repository in `org/repo` form, or null if the run started without a repo.",
)
origin_product = serializers.CharField(help_text="`Task.OriginProduct` (`slack` for slack-originated tasks).")
created_at = serializers.DateTimeField(help_text="When the task was created (server-side timestamp).")
url = serializers.CharField(help_text="Absolute URL to the task detail page in the PostHog app.")
admin_url = serializers.CharField(help_text="Absolute URL to the Task row in Django admin.")
class SlackThreadContextRepoResearchSerializer(serializers.Serializer):
"""The internal sandbox run the discovery agent used to pick this run's repo.
Only present when the originating mention was ambiguous (multiple candidate
repos, no explicit mention) — that's the only path that spins up a research
sandbox. Null otherwise.
"""
task_id = serializers.CharField(help_text="UUID of the internal repo-research Task.")
run_id = serializers.CharField(help_text="UUID of the internal repo-research TaskRun.")
status = serializers.CharField(
allow_null=True,
help_text="Research run status, or null if the run row could not be loaded.",
)
task_processing_workflow_id = serializers.CharField(
help_text=(
"Temporal workflow id for the research sandbox run (`task-processing-<task_id>-<run_id>`, "
"or a caller-prefixed variant)."
),
)
task_processing_workflow_url = serializers.CharField(
allow_null=True,
help_text="Full Temporal Web UI URL for the research workflow; null when `TEMPORAL_UI_HOST` is unset.",
)
sandbox_url = serializers.CharField(
allow_null=True,
help_text="Live sandbox tunnel URL for the research run, when one was attached.",
)
task_view_url = serializers.CharField(
help_text="Absolute URL to the research task detail page (carries `?ph_debug=true`).",
)
log_url = serializers.CharField(
allow_null=True,
help_text="Presigned S3 URL for the research run's JSONL log transcript (valid ~1 hour).",
)
class SlackThreadContextRunSerializer(serializers.Serializer):
"""One TaskRun and its associated Temporal workflow handles."""
id = serializers.CharField(help_text="UUID of the TaskRun row.")
status = serializers.CharField(help_text="Run status (queued/in_progress/completed/failed/…).")
created_at = serializers.DateTimeField(help_text="When the run was created.")
completed_at = serializers.DateTimeField(
allow_null=True,
help_text="When the run reached a terminal state, or null while still running.",
)
sandbox_url = serializers.CharField(
allow_null=True,
help_text="Live sandbox tunnel URL, when one was attached.",
)
pr_url = serializers.CharField(
allow_null=True,
help_text="PR URL produced by the run, when one was opened.",
)
error_message = serializers.CharField(
allow_null=True,
help_text="Error captured on terminal failure, or null on success.",
)
task_processing_workflow_id = serializers.CharField(
help_text=(
"Temporal workflow id for the sandbox/agent run (`task-processing-<task_id>-<run_id>`, "
"or a caller-prefixed variant)."
),
)
task_processing_workflow_url = serializers.CharField(
allow_null=True,
help_text="Full Temporal Web UI URL for the task-processing workflow; null when `TEMPORAL_UI_HOST` is unset.",
)
mention_workflow_id = serializers.CharField(
allow_null=True,
help_text=(
"Temporal workflow id of the Slack mention that dispatched this run "
"(`slack-app-mention-processing-<workspace>:<event_id_or_channel:ts>`). Null for runs "
"created before this field was persisted."
),
)
mention_workflow_url = serializers.CharField(
allow_null=True,
help_text="Full Temporal Web UI URL for the mention dispatch workflow; null when unavailable.",
)
task_view_url = serializers.CharField(help_text="Absolute URL to the task detail page focused on this run.")
log_url = serializers.CharField(
allow_null=True,
help_text="Presigned S3 URL for the run's full JSONL log transcript (valid ~1 hour).",
)
repo_research = SlackThreadContextRepoResearchSerializer(
allow_null=True,
help_text="The discovery-agent sandbox that picked this run's repo, when the mention was ambiguous.",
)
admin_url = serializers.CharField(
help_text="Absolute URL to the TaskRun row in Django admin (includes a log download action).",
)
class SlackThreadContextResponseSerializer(serializers.Serializer):
"""Top-level response for the slack-thread debug endpoint."""
thread = SlackThreadContextThreadSerializer(help_text="Slack-side identifiers and the mapping metadata.")
task = SlackThreadContextTaskSerializer(
allow_null=True,
help_text="Linked PostHog Task. Null when no mapping was found for the thread.",
)
runs = SlackThreadContextRunSerializer(
many=True,
help_text="All runs on the task, oldest first. Empty when no mapping was found.",
)
class AgentProxyProcessKilledSerializer(serializers.Serializer):
comm = serializers.CharField(max_length=64, help_text="Command name of the root process the watchdog stopped.")
signal = serializers.CharField(
max_length=16, help_text="Last signal the watchdog sent, such as SIGTERM or SIGKILL."
)
tree_rss_bytes = serializers.IntegerField(
min_value=0, help_text="Resident memory of the stopped process tree, in bytes."
)
memory_current_bytes = serializers.IntegerField(
min_value=0, help_text="Sandbox memory in use when the watchdog acted, in bytes."
)
memory_limit_bytes = serializers.IntegerField(min_value=0, help_text="Sandbox memory limit, in bytes.")
class AgentProxyCallbackKind(models.TextChoices):
HEARTBEAT = "heartbeat", "Heartbeat"
AWAITING_INPUT = "awaiting_input", "Awaiting input"
PERMISSION_REQUESTED = "permission_requested", "Permission requested"
TURN_FAILED = "turn_failed", "Turn failed"
COMMAND_DISPATCHED = "command_dispatched", "Command dispatched"
AGENT_ACTIVITY = "agent_activity", "Agent activity"
BUDGET_STEER = "budget_steer", "Budget steer"
PROCESS_KILLED = "process_killed", "Process killed"
class AgentProxyCallbackRequestSerializer(serializers.Serializer):
"""Request body for the agent-proxy side-effect callback.
Called by the standalone Node agent-proxy after it accepts an ingest event
that triggers a Temporal heartbeat or an awaiting-input push notification.
The request is authenticated with the original sandbox event ingest JWT so
Django can re-validate claims without an extra token round-trip.
"""
kind = serializers.ChoiceField(
choices=AgentProxyCallbackKind.choices,
help_text=(
"Side effect to dispatch. 'heartbeat' signals the Temporal workflow to reset its "
"inactivity timer. 'awaiting_input' fires a mobile push notification when an "
"interactive run finishes a turn and is waiting for user input. 'permission_requested' fires a "
"'needs your input' push when an interactive run waits on a permission request or a question. "
"'turn_failed' fails "
"the run outright when a pi turn ends in a runtime error. 'command_dispatched' "
"and 'agent_activity' record boot milestones. 'budget_steer' captures the agent's budget warning. "
"'process_killed' captures a sandbox memory watchdog kill."
),
)
agent_active = serializers.BooleanField(
help_text=(
"Whether the agent is currently active (true) or idle (false). "
"This is true for 'heartbeat' and 'agent_activity', and false otherwise."
),
)
activity_started = serializers.BooleanField(
required=False,
default=False,
help_text="Whether this heartbeat marks new activity after the agent was idle, bypassing throttling.",
)
turn_completed = serializers.BooleanField(
required=False,
default=True,
help_text=(
"Whether 'awaiting_input' reports a completed turn. Set false for an idle sandbox resume "
"to mark the agent idle without sending a completion notification or updating activity."
),
)
turn_succeeded = serializers.BooleanField(
required=False,
default=False,
help_text=(
"Whether 'awaiting_input' reports a turn that ended with the 'end_turn' stop reason. "
"False for any other stop reason."
),
)
task_id = serializers.CharField(
max_length=36,
help_text="UUID of the Task that owns this run. Must match the JWT claim.",
)
team_id = serializers.IntegerField(
min_value=1,
help_text="Numeric team (project) ID. Must match the JWT claim.",
)
sequence = serializers.IntegerField(
required=False,
min_value=1,
help_text=(
"Event sequence used to deduplicate a budget steer or a process kill. "
"Also sent with 'permission_requested' to identify the event."
),
)
request_id = serializers.CharField(
required=False,
max_length=200,
help_text="ID of the pending permission request that 'permission_requested' reports.",
)
timestamp = serializers.DateTimeField(required=False, help_text="Original event time, preserved across retries.")
stage = serializers.CharField(required=False, help_text="Budget stage: warn or critical.")
mode = serializers.CharField(required=False, help_text="Budget steer mode: publish or wrap_up.")
delivered = serializers.BooleanField(required=False, help_text="Whether the steer reached the agent.")
spent_usd = serializers.FloatField(
required=False, min_value=0, help_text="Estimated spend when the steer was sent."
)
cap_usd = serializers.FloatField(required=False, min_value=0, help_text="Gateway spending cap for this run.")
threshold_spent_usd = serializers.FloatField(
required=False, min_value=0, help_text="Estimated spend when the budget stage was reached."
)
threshold_at = serializers.DateTimeField(required=False, help_text="Time when the budget stage was reached.")
delivered_at = serializers.DateTimeField(required=False, help_text="Time when the steer reached the agent.")
process_killed = AgentProxyProcessKilledSerializer(
required=False, help_text="The kill the sandbox memory watchdog reported. Required for 'process_killed'."
)
class AgentProxyCallbackResponseSerializer(serializers.Serializer):
"""Response from the agent-proxy side-effect callback."""
dispatched = serializers.BooleanField(
help_text="True when the requested side effect was dispatched; false when skipped (e.g. run not found)."
)
class TasksAIRunPreferencesSerializer(serializers.Serializer):
"""The default AI run selection stored at team or user level.
Write payload for the tasks config endpoints and the `ai_run_preferences` block of
their responses. What a complete selection is depends on the harness: an ACP default
sets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send
every field as null to clear a stored preference.
"""
REASONING_EFFORT_CHOICES = TASK_RUN_REASONING_EFFORT_CHOICES
runtime = serializers.ChoiceField(
choices=tasks_facade.TaskRuntime.choices,
required=False,
allow_null=True,
default=None,
help_text=(
"Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the "
"Pi harness. Defaults to 'acp' when omitted."
),
)
runtime_adapter = serializers.ChoiceField(
choices=RuntimeAdapter.choices,
required=False,
allow_null=True,
default=None,
help_text=(
"Default agent runtime adapter for new task runs. Use 'claude' for the Claude "
"runtime or 'codex' for the Codex runtime. Must be set together with `model`, and "
"must be null when `runtime` is 'pi'."
),
)
model = serializers.CharField(
required=False,
allow_null=True,
allow_blank=False,
default=None,
help_text=(
"Default LLM model identifier for new task runs. Must be set together with "
"`runtime_adapter` on the ACP harness, and is required on its own for a Pi default."
),
)
reasoning_effort = serializers.ChoiceField(
choices=REASONING_EFFORT_CHOICES,
required=False,
allow_null=True,
default=None,
help_text=(
"Default reasoning effort for models that expose an effort control. A Pi default "
"stores a Pi thinking level here, which also allows 'off' and 'minimal'."
),
)
class TasksResolvedAIRunDefaultsSerializer(serializers.Serializer):
"""The AI run selection a new run will effectively use when the caller pins nothing,
plus which preference level supplied it."""
# Not bound to `ResolvedAIRunConfig` via DataclassSerializer: that dataclass also carries the
# internal `explicit` resolution state this endpoint never returns, and its per-field defaults
# would mark every field optional when the response always sends all four.
runtime = serializers.CharField(
help_text="Harness the effective default runs on: 'acp' or 'pi'. 'acp' when no preference is stored."
)
runtime_adapter = serializers.CharField(
allow_null=True,
help_text="Effective default runtime adapter, or null when no preference is stored or the harness is Pi.",
)
model = serializers.CharField(
allow_null=True, help_text="Effective default model identifier, or null when no preference is stored."
)
reasoning_effort = serializers.CharField(
allow_null=True, help_text="Effective default reasoning effort, or null when unset or unsupported."
)
# `Field.source` exists on the base class, but the serializer metaclass pops declared fields off the
# class body before it ever binds, so there is no shadowing at runtime — only mypy sees a clash.
source = serializers.ChoiceField( # type: ignore[assignment]
choices=["user", "team", "none"],
help_text="Preference level that supplied the default: the caller's own per-project preference ('user'), the project default ('team'), or 'none'.",
)
class TasksAgentInstructionsSerializer(serializers.Serializer):
"""Markdown instructions that PostHog cloud agents load as their user-level AGENTS.md in Tasks runs."""
agent_instructions = serializers.CharField(
allow_blank=True,
max_length=AGENT_INSTRUCTIONS_MAX_LENGTH,
trim_whitespace=False,
help_text=(
"Markdown instructions that PostHog cloud agents read in every eligible Tasks run, the same way "
"a local agent reads AGENTS.md. Send an empty string to clear."
),
)
@extend_schema_serializer(many=False)
class TasksTeamConfigResponseSerializer(serializers.Serializer):
"""Team-level tasks configuration."""
ai_run_preferences = TasksAIRunPreferencesSerializer(
help_text="Project-wide default AI run triple; all fields null when unset."
)
agent_instructions = serializers.CharField(
help_text=(
"Project instructions that PostHog cloud agents read in every eligible Tasks run, including autonomous "
"runs such as scouts and loops. Empty when unset."
)
)
@extend_schema_serializer(many=False)
class TasksTaskDefaultsSerializer(serializers.Serializer):
"""The requesting user's per-project task defaults, shared by PostHog Desktop and the web app."""
start_in_plan_mode = serializers.BooleanField(
allow_null=True,
help_text=(
"When true, new tasks start in plan mode: the agent makes a plan and waits for approval. "
"Null when you never set it."
),
)
auto_publish_cloud_runs = serializers.BooleanField(
allow_null=True,
help_text="When true, a cloud run that changes code always opens a draft pull request. Null when you never set it.",
)
default_cloud_target = serializers.RegexField(
regex=CLOUD_TARGET_PATTERN,
allow_null=True,
help_text=(
"The cloud target new tasks start on, as `environment:<sandbox environment id>` or "
"`image:<custom image id>`. Null means the default sandbox. Clients fall back to the default "
"sandbox when the target no longer exists."
),
)
class TasksTaskDefaultsUpdateSerializer(TasksTaskDefaultsSerializer):
"""A partial update of the requesting user's task defaults. Fields left out keep their stored value."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.required = False
field.allow_null = False
self.fields["default_cloud_target"].allow_null = True
class TasksUserConfigResponseSerializer(serializers.Serializer):
"""The requesting user's per-project tasks configuration."""
ai_run_preferences = TasksAIRunPreferencesSerializer(
help_text="The requesting user's per-project default AI run triple; all fields null when unset."
)
resolved_ai_run_defaults = TasksResolvedAIRunDefaultsSerializer(
help_text="The defaults a new run will use when no explicit runtime selection is sent."
)
agent_instructions = serializers.CharField(
help_text=(
"Your personal instructions, which PostHog cloud agents read in Tasks runs you start, after the project "
"instructions. Anyone who continues a task you started can see them. Empty when unset."
)
)
task_defaults = TasksTaskDefaultsSerializer(
help_text="Your per-project defaults for new tasks. Unset defaults are false."
)
class DesktopGatewayTokenRefusalSerializer(serializers.Serializer):
enabled = serializers.BooleanField()
reason = serializers.CharField()
detail = serializers.CharField(required=False)
access = serializers.DictField(required=False)
class DesktopGatewayTokenSerializer(serializers.Serializer):
enabled = serializers.BooleanField()
token = serializers.CharField()
expires_at = serializers.CharField()
cap_usd = serializers.JSONField(allow_null=True)
gateway_url = serializers.CharField()
product = serializers.CharField()
team_id = serializers.IntegerField()
plan = serializers.CharField()
allowed_models = serializers.ListField(child=serializers.CharField())
product_models = serializers.ListField(child=serializers.CharField())
class DesktopUsageSerializer(serializers.Serializer):
product = serializers.CharField()
user_id = serializers.IntegerField()
burst = serializers.JSONField()
sustained = serializers.JSONField()
ai_credits = serializers.JSONField()
is_rate_limited = serializers.BooleanField()
is_pro = serializers.BooleanField()
code_usage_subscribed = serializers.BooleanField()
billing_period_end = serializers.CharField(allow_null=True)