: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
"""
Sandbox module - provides the Sandbox class for task execution.
This module exports:
- Sandbox: The sandbox class (ModalSandbox in production, DockerSandbox for local dev)
- SandboxConfig: Configuration for creating sandboxes
- SandboxStatus: Enum for sandbox states
- SandboxTemplate: Enum for sandbox templates
- ExecutionResult: Result of command execution
"""
from __future__ import annotations
import os
import re
import json
import shlex
import functools
import threading
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterable
from contextlib import AbstractContextManager, nullcontext
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from types import TracebackType
from typing import TYPE_CHECKING, Any, Protocol, Self
from django.conf import settings
import structlog
from pydantic import BaseModel, model_validator
from posthog.dataclasses import frozen
from products.tasks.backend.constants import (
DEFAULT_SANDBOX_WORKING_DIR,
DEV_STACK_IMAGE_NAME,
SANDBOX_REPOSITORIES_ROOT,
)
from products.tasks.backend.logic.services.local_skills import BUNDLED_SKILLS_PATHS, ENV_DISABLE_BUNDLED_SKILLS
from products.tasks.backend.logic.services.sandbox_config import (
BURSTABLE_REQUEST_CPU_CORES,
BURSTABLE_REQUEST_MEMORY_MB,
DEV_STACK_CPU_REQUEST_CORES,
DEV_STACK_MEMORY_GB,
SANDBOX_TTL_SECONDS,
VM_SANDBOX_CPU_CORES,
)
from products.tasks.backend.logic.services.startup_failure import raise_startup_failure
from products.tasks.backend.model_catalog import CLAUDE, is_anthropic_served_model
if TYPE_CHECKING:
from products.tasks.backend.temporal.process_task.utils import McpServerConfig
SANDBOX_BASE_DOCKERFILE_PATH = Path(__file__).resolve().parents[2] / "sandbox" / "images" / "Dockerfile.sandbox-base"
def read_pinned_agent_version(dockerfile_path: Path) -> str | None:
try:
source = dockerfile_path.read_text(encoding="utf-8")
except OSError:
return None
match = re.search(r"^ARG AGENT_VERSION=(\S+)", source, re.MULTILINE)
return match.group(1) if match else None
@functools.cache
def pinned_agent_version() -> str | None:
return read_pinned_agent_version(SANDBOX_BASE_DOCKERFILE_PATH)
@frozen
class AgentServerResult:
"""Result from starting an agent server in a sandbox."""
url: str
token: str | None = field(default=None, repr=False)
class SandboxStatus(str, Enum):
RUNNING = "running"
SHUTDOWN = "shutdown"
class SandboxTemplate(str, Enum):
DEFAULT_BASE = "default_base"
NOTEBOOK_BASE = "notebook_base"
PI_BASE = "pi_base"
AUTORESEARCH_BASE = "autoresearch_base"
VM_BASE = "vm_base"
STREAMLIT_BASE = "streamlit_base"
# Minimal template (git, node, uv — no agent server, no skills). For review/exec
# sandboxes like stamphog that never run the agent server. See
# Dockerfile.sandbox-slim and modal_sandbox.py's SLIM_BASE image definition.
SLIM_BASE = "slim_base"
CANVAS_BUILD = "canvas_build"
# SLIM_BASE plus a uv cache that already holds the stamphog review engine's pinned deps,
# so the engine's `uv run` starts without a download.
STAMPHOG_REVIEW = "stamphog_review"
# Templates whose image hosts the task agent server, so a task can ask for them. The
# notebook, streamlit, slim and canvas images omit the server on purpose, pi has no Modal
# image, and VM_BASE bakes in Docker and forces the VM runtime, which only the server-side
# VM routing gate may select.
TASK_AGENT_TEMPLATES: frozenset[SandboxTemplate] = frozenset(
{SandboxTemplate.DEFAULT_BASE, SandboxTemplate.AUTORESEARCH_BASE}
)
def parse_requested_sandbox_template(value: str | None) -> SandboxTemplate:
"""Resolve a template a caller asked for on a task; anything outside ``TASK_AGENT_TEMPLATES`` is refused."""
if value is None:
return SandboxTemplate.DEFAULT_BASE
try:
template = SandboxTemplate(value)
except ValueError:
raise ValueError(f"Unknown sandbox template: {value!r}")
if template not in TASK_AGENT_TEMPLATES:
raise ValueError(f"Sandbox template {value!r} cannot be requested per task")
return template
class SandboxWorkload(str, Enum):
"""Which provider-side project a sandbox is booked against, independent of its image.
Modal groups sandboxes and their cost by app. The template already picks an app for the
product-specific images; this picks one for workloads that share an image but should be
metered apart.
"""
DEFAULT = "default"
SELF_DRIVING = "self_driving"
SELF_DRIVING_ORIGIN_PRODUCTS: frozenset[str] = frozenset(
{
# Signals report research + repo selection
"signal_report",
# Headless Signals scouts, and the headless scan that pre-computes scout suggestions
"signals_scout",
"scout_suggestions",
# ReviewHog's per-chunk review, blind-spot, and validation sandboxes
"review_hog",
}
)
"""Origin products whose sandboxes are booked against the self-driving provider project.
Wider than the self-driving *quota* gate (`enforce_self_driving_quota.py`), which only covers the
billable implementation-PR run: this is every sandbox the fleet opens, research and review included.
Held as strings rather than ``Task.OriginProduct`` members to keep the model layer off this module's
import path; a test pins them to the enum so a rename can't drop a product off the fleet.
"""
FULL_HISTORY_ORIGIN_PRODUCTS: frozenset[str] = frozenset(
{
# Signals report research reads history for `git blame`
"signal_report",
# A pinned scout asks the same questions of the tree: `git log`, `git blame`, `--since`
"signals_scout",
}
)
"""Origin products whose sandboxes clone the full commit history instead of `--depth 1`.
Every other origin keeps the fast-boot shallow clone. Nobody watches a fleet run, so a slower
boot costs less than the unshallow fetch a skill body pays mid-run to get history back. Held as
strings for the same reason as ``SELF_DRIVING_ORIGIN_PRODUCTS``; a test pins them to the enum.
"""
def workload_for_origin_product(origin_product: str | None) -> SandboxWorkload:
if origin_product in SELF_DRIVING_ORIGIN_PRODUCTS:
return SandboxWorkload.SELF_DRIVING
return SandboxWorkload.DEFAULT
def needs_full_history(origin_product: str | None) -> bool:
return origin_product in FULL_HISTORY_ORIGIN_PRODUCTS
class ExecutionResult(BaseModel):
stdout: str
stderr: str
exit_code: int
error: str | None = None
class ExecutionStream(Protocol):
def iter_stdout(self) -> Iterable[str]: ...
def wait(self) -> ExecutionResult: ...
@dataclass(frozen=True)
class SandboxResources:
"""Optional compute overrides for a task's sandbox. Unset fields keep the
`SandboxConfig` defaults — callers pass only what they want to change."""
cpu_cores: float | None = None
memory_gb: float | None = None
class SandboxConfig(BaseModel):
base_image_reference: str | None = None
require_snapshot: bool = False
name: str
template: SandboxTemplate = SandboxTemplate.DEFAULT_BASE
# Decides which Modal app owns the box, and with it how its cost is attributed. Changes
# nothing about the box itself — same image, same resources, same isolation.
workload: SandboxWorkload = SandboxWorkload.DEFAULT
default_execution_timeout_seconds: int = 10 * 60 # 10 minutes
environment_variables: dict[str, str] | None = None
snapshot_id: str | None = None
snapshot_external_id: str | None = None
resume_snapshot_external_id: str | None = None
snapshot_mount_path: str | None = None
snapshot_source: str = "none"
snapshot_restored: bool = False
ttl_seconds: int = SANDBOX_TTL_SECONDS
metadata: dict[str, str] | None = None
memory_gb: float = 16
cpu_cores: float = 4
disk_size_gb: float = 64
# When True, request a small floor and let the box burst up to `cpu_cores` / `memory_gb`
# (the limit); Modal bills max(request, actual). When False, request == limit (fixed size).
burstable_resources: bool = False
# Request floor used when `burstable_resources` is True: the box reserves this much and bursts
# up to `cpu_cores` / `memory_gb`. Read through the `effective_*_request` properties, which
# apply the limit clamp and the VM memory pin.
cpu_request_cores: float = BURSTABLE_REQUEST_CPU_CORES
memory_request_mb: int = BURSTABLE_REQUEST_MEMORY_MB
vm_runtime: bool = False
outbound_domain_allowlist: list[str] | None = None
network_policy_fingerprint: str | None = None
# gVisor only. An empty domain allowlist means unrestricted network in
# Modal, so callers that require no egress must state it explicitly.
block_network: bool = False
# VM runtime only — custom images layer on the VM base; snapshot restores take precedence.
custom_image_name: str | None = None
# Set by the provider when the sandbox could not be created from the intended image and a
# downgraded one was used instead (e.g. published custom image -> plain base). Human-readable,
# surfaced in the run log so image downgrades are never silent.
image_fallback: str | None = None
dev_stack_present: bool | None = None
# Hogland only: provision from the pluggable-memory golden (boots small, hot-adds
# guest RAM up to the cap) instead of the fixed-size default golden. Set from the
# tasks-hogland-hotplug-golden flag at context time; ignored by other providers.
use_hotplug_golden: bool = False
@model_validator(mode="before")
@classmethod
def _default_vm_cpu(cls, data: object) -> object:
if (
isinstance(data, dict)
and "cpu_cores" not in data
and (
data.get("vm_runtime")
or data.get("template") in (SandboxTemplate.VM_BASE, SandboxTemplate.VM_BASE.value)
)
):
return {**data, "cpu_cores": VM_SANDBOX_CPU_CORES}
return data
@property
def is_vm(self) -> bool:
return self.vm_runtime or self.template == SandboxTemplate.VM_BASE
@property
def is_dev_stack_image(self) -> bool:
if not self.is_vm:
return False
if self.dev_stack_present is not None:
return self.dev_stack_present
return self.custom_image_name == DEV_STACK_IMAGE_NAME
@property
def applies_dev_stack_floors(self) -> bool:
return self.is_dev_stack_image and self.workload == SandboxWorkload.DEFAULT
@model_validator(mode="after")
def _enforce_dev_stack_memory_floor(self) -> Self:
if self.applies_dev_stack_floors:
self.memory_gb = max(self.memory_gb, DEV_STACK_MEMORY_GB)
return self
@property
def effective_cpu_request_cores(self) -> float:
"""CPU floor the provider actually reserves when burstable: the configured request,
raised to the dev-stack floor on default-workload boxes, clamped to the limit."""
floor = float(self.cpu_request_cores)
if self.applies_dev_stack_floors:
floor = max(floor, DEV_STACK_CPU_REQUEST_CORES)
return min(floor, float(self.cpu_cores))
@property
def effective_memory_request_mb(self) -> int:
"""Memory floor the provider actually reserves when burstable. VM memory can't burst,
so a VM's request is pinned to its limit; gVisor requests are clamped to the limit."""
memory_limit_mb = int(self.memory_gb * 1024)
if self.is_vm:
return memory_limit_mb
return min(int(self.memory_request_mb), memory_limit_mb)
WORKING_DIR = DEFAULT_SANDBOX_WORKING_DIR
REPO_READY_FILE = f"{WORKING_DIR}/.repo-ready"
PUBLIC_SANDBOX_REPOS: frozenset[str] = frozenset({"posthog/hedgebox", "posthog/.github"})
"""Repos the sandbox is allowed to clone unauthenticated, even when the team has no GitHub integration"""
# TODO: Remove `posthog/.github` when we switch repo discovery to repo-less agent (now it works as a lightweight dummy)
# this helps redact sensitive environment variables for logging
SENSITIVE_SANDBOX_ENV_NAMES: frozenset[str] = frozenset(
{
"GITHUB_TOKEN",
"POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN",
"POSTHOG_TASK_RUN_SESSION_TOKEN",
"POSTHOG_WIZARD_API_KEY",
}
)
SHELL_ARGUMENT_VALUE_PATTERN = r"'(?:[^']|'\"'\"')*'|\"(?:\\.|[^\"])*\"|\S+"
SENSITIVE_SANDBOX_ENV_PATTERN = re.compile(
r"(?P<name>" + "|".join(re.escape(name) for name in SENSITIVE_SANDBOX_ENV_NAMES) + r")="
rf"(?P<value>{SHELL_ARGUMENT_VALUE_PATTERN})"
)
SENSITIVE_AGENT_RUNTIME_ARGUMENT_PATTERN = re.compile(
rf"(?P<name>--mcpServers)\s+(?P<value>{SHELL_ARGUMENT_VALUE_PATTERN})"
)
SENSITIVE_FILE_HEREDOC_PATTERN = re.compile(
r"(?P<prefix><<'POSTHOG_FILE_EOF'\n).*?(?P<suffix>\nPOSTHOG_FILE_EOF)", re.DOTALL
)
GITHUB_CLONE_TOKEN_PATTERN = re.compile(r"(?P<prefix>https://x-access-token:)[^@\s]+(?P<suffix>@github\.com/)")
def is_public_sandbox_repo(repository: str | None) -> bool:
return repository is not None and repository.lower() in PUBLIC_SANDBOX_REPOS
def sandbox_repo_path(repository: str) -> str:
"""Absolute path an ``org/repo`` is cloned to inside the sandbox (the agent-server's cwd)."""
org, repo = repository.lower().split("/")
return f"{SANDBOX_REPOSITORIES_ROOT}/{org}/{repo}"
def redact_sandbox_command(command: str) -> str:
redacted = command
for pattern, substitution in (
(SENSITIVE_SANDBOX_ENV_PATTERN, r"\g<name>=<redacted>"),
(SENSITIVE_AGENT_RUNTIME_ARGUMENT_PATTERN, r"\g<name> <redacted>"),
(SENSITIVE_FILE_HEREDOC_PATTERN, r"\g<prefix><redacted>\g<suffix>"),
(GITHUB_CLONE_TOKEN_PATTERN, r"\g<prefix><redacted>\g<suffix>"),
):
redacted = pattern.sub(substitution, redacted)
return redacted
def build_agent_runtime_env_prefix(
*,
interaction_origin: str | None = None,
agent_runtime: str | None = None,
sandbox_id: str | None = None,
sandbox_runtime: str | None = None,
runtime_adapter: str | None = None,
provider: str | None = None,
model: str | None = None,
reasoning_effort: str | None = None,
service_tier: str | None = None,
context_window: str | None = None,
fast_mode: bool | None = None,
initial_permission_mode: str | None = None,
event_ingest_token: str | None = None,
task_run_session_token: str | None = None,
event_ingest_url: str | None = None,
rtk_enabled: bool = True,
benjamin_enabled: bool = False,
pi_acp_conversation: bool = False,
unset_bedrock: bool = False,
) -> str:
env_vars = {
"POSTHOG_CODE_INTERACTION_ORIGIN": interaction_origin,
"POSTHOG_AGENT_RUNTIME": agent_runtime,
"POSTHOG_SANDBOX_ID": sandbox_id,
"POSTHOG_SANDBOX_RUNTIME": sandbox_runtime,
"POSTHOG_CODE_RUNTIME_ADAPTER": runtime_adapter,
"POSTHOG_CODE_PROVIDER": provider,
"POSTHOG_CODE_MODEL": model,
"POSTHOG_CODE_REASONING_EFFORT": reasoning_effort,
# OpenAI service tier for codex runs ("default" | "priority" | "flex"); ignored by the
# claude adapter. Codex itself drops a tier the model catalogue doesn't advertise.
"POSTHOG_CODE_SERVICE_TIER": service_tier,
"POSTHOG_CODE_CONTEXT_WINDOW": context_window,
# Explicit false pins fast mode off even if a stale env value survives in a resumed sandbox.
"POSTHOG_CODE_FAST_MODE": None if fast_mode is None else ("true" if fast_mode else "false"),
"POSTHOG_CODE_INITIAL_PERMISSION_MODE": initial_permission_mode,
"POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN": event_ingest_token,
"POSTHOG_TASK_RUN_SESSION_TOKEN": task_run_session_token,
"POSTHOG_TASK_RUN_EVENT_INGEST_URL": event_ingest_url,
"POSTHOG_TASK_RUN_EVENT_INGEST_KEEP_STREAM_OPEN": (
"false" if settings.DEBUG and not event_ingest_url else "true"
),
# Set explicitly in both states: "0" opts the run out, "1" pins auto-detection on
# even if a stale env value survives in a resumed sandbox.
"POSTHOG_RTK": "1" if rtk_enabled else "0",
"POSTHOG_BENJAMIN": "1" if benjamin_enabled else "0",
"POSTHOG_PI_CONVERSATION_FORMAT": "acp" if pi_acp_conversation else "pi",
}
if runtime_adapter == CLAUDE and model and not is_anthropic_served_model(model):
env_vars["CLAUDE_CODE_AUTO_MODE_SERVER"] = "0"
env_vars["CLAUDE_CODE_AUTO_MODE_MODEL"] = model
assignments = " ".join(
f"{name}={shlex.quote(value)}" for name, value in env_vars.items() if value is not None and value != ""
)
# Route the agent through the PostHog LLM gateway instead of direct Bedrock:
# unset the box profile's Bedrock vars so the Claude CLI falls back to the
# gateway (ANTHROPIC_BASE_URL/ANTHROPIC_AUTH_TOKEN). Direct Bedrock from the
# box needs AWS Marketplace model access plus SigV4-signing the
# x-posthog-property-* headers (which AWS strips), so the gateway path avoids
# both and matches the Modal backend.
unset_flags = "-u CLAUDE_CODE_USE_BEDROCK -u AWS_CONTAINER_CREDENTIALS_FULL_URI" if unset_bedrock else ""
body = f"{unset_flags} {assignments}".strip()
return f"env {body} " if body else ""
AGENT_SERVER_BINARY_PATH = "/scripts/node_modules/.bin/agent-server"
AGENT_SERVER_CAPABILITY_TOKENS: dict[str, str] = {
"auto_publish": "autoPublish",
"exec_permission_regex": "posthogExecPermissionRegex",
"pi_runtime": "POSTHOG_AGENT_RUNTIME",
"prewarmed_resume_message_driven": "prewarmedResumeMessageDriven",
}
def build_bundled_skills_clear_command() -> str:
"""Delete the bundled skill folders when the sandbox environment asks for it.
The check runs inside the sandbox: a sandbox rehydrated by id carries no config env
vars, but the container environment still holds the value the launcher set.
"""
paths = " ".join(shlex.quote(path) for path in BUNDLED_SKILLS_PATHS)
return (
"export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin; "
f'if [ "${ENV_DISABLE_BUNDLED_SKILLS}" = "1" ]; then /usr/bin/rm -rf {paths} && /usr/bin/mkdir -p {paths}; fi'
)
def build_agent_server_capability_probe(capability: str) -> str:
"""Sandboxes restored from old snapshots can carry an agent-server that rejects unknown
CLI options, so probe the installed binary before passing a flag such as --autoPublish;
unsupported binaries degrade instead of crashing at launch."""
return f"grep -q {shlex.quote(AGENT_SERVER_CAPABILITY_TOKENS[capability])} {AGENT_SERVER_BINARY_PATH}"
class SandboxBase(ABC):
id: str
config: SandboxConfig
supports_creation_cancellation = False
creation_timeout_seconds = 300
# When True, the agent runtime is launched with the box's Bedrock env unset,
# so the Claude CLI routes through the PostHog LLM gateway instead of direct
# Bedrock. hogland opts in (see HoglandSandbox); Modal/Docker already use the
# gateway.
disable_direct_bedrock = False
@staticmethod
def creation_cancellation_scope(cancel_event: threading.Event) -> AbstractContextManager[None]:
return nullcontext()
@property
@abstractmethod
def sandbox_url(self) -> str | None:
"""Return the URL for connecting to the agent server, or None if not available."""
...
@staticmethod
@abstractmethod
def create(config: SandboxConfig) -> SandboxBase: ...
@staticmethod
@abstractmethod
def get_by_id(sandbox_id: str) -> SandboxBase: ...
@staticmethod
@abstractmethod
def delete_snapshot(external_id: str) -> None: ...
@abstractmethod
def get_status(self) -> SandboxStatus: ...
@abstractmethod
def execute(self, command: str, timeout_seconds: int | None = None) -> ExecutionResult: ...
def execute_in_task_filesystem(self, command: str, timeout_seconds: int | None = None) -> ExecutionResult:
return self.execute(command, timeout_seconds=timeout_seconds)
@abstractmethod
def execute_stream(self, command: str, timeout_seconds: int | None = None) -> ExecutionStream: ...
@abstractmethod
def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult: ...
def stop_agent_server(self) -> ExecutionResult:
"""Stop the agent server gracefully so it can flush terminal events."""
return self.execute(
"pkill -TERM -f '[a]gent-server' 2>/dev/null || true; "
"for _ in $(seq 1 80); do "
"pgrep -f '[a]gent-server' >/dev/null || exit 0; "
"sleep 0.5; "
"done; "
"exit 1",
timeout_seconds=45,
)
def launch_dev_stack_bootstrap(self) -> bool:
"""Fire-and-forget the baked dev-stack bootstrap helper when this image carries it.
The prebaked dev-stack image ships /usr/local/bin/bootstrap-dev-stack (see
bake-posthog-dev-stack.sh): it restores the compose /etc/hosts aliases the sandbox
boot wiped and starts dockerd. Launching it detached at provision time overlaps
that warmup with the repo clone and agent-server boot, so a task-time `hogli start`
finds dockerd already up. The helper is idempotent — an agent running it again per
AGENTS.md just blocks until the warmup completes.
Best-effort by design: returns whether the helper was found and launched, and never
raises. A missed warmup only costs the overlap; the agent-side bootstrap still works.
"""
# Only a sandbox that actually booted the PostHog-published dev-stack image gets
# its bootstrap run by the backend. This hook runs after credentials land in the
# sandbox env, so executing a script from any less-trusted filesystem would hand
# its author code execution with another member's secrets. Two checks:
# - the reserved name (user images always publish as posthog-sandbox-custom-*),
# with the absolute path below avoiding PATH shadowing;
# - not a filesystem-snapshot restore: such a restore boots a mutable snapshot
# of a prior run — one that processed untrusted repo content and could have
# replaced the helper file itself. Directory restores only mount the workspace
# dir (ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS), leaving the helper the
# vetted image's own binary, so the warmup stays on for them — but the
# workspace is still attacker-controlled, so the launcher below scrubs the
# environment (fixed PATH, no credentials) rather than trusting it.
restored_untrusted_filesystem = (
self.config.snapshot_restored and self.config.resume_snapshot_external_id is None
)
if (
not self.config.is_vm
or self.config.custom_image_name != DEV_STACK_IMAGE_NAME
or restored_untrusted_filesystem
):
return False
try:
# Exit 3 = helper not present (downgraded to the plain VM base, or a pre-helper
# image) — an expected skip, not a failure. setsid + redirects detach the helper
# from this exec, which the sandbox runtime reaps as soon as the command returns.
#
# Run the helper through `/usr/bin/env -i` (absolute — a user PATH cannot shadow
# the launcher) with a fixed system PATH and no other environment. This is what
# makes the directory-restore case above safe: a directory resume mounts the
# untrusted workspace at /tmp/workspace, and PATH is a settable sandbox env var,
# so without scrubbing the helper's `start-dockerd`/`docker` lookups could resolve
# an attacker binary from the workspace — and would run it with the injected
# POSTHOG_PERSONAL_API_KEY / GITHUB_TOKEN. `env -i` drops those credentials and the
# user PATH; the fixed PATH resolves only real system binaries (start-dockerd lives
# in /usr/local/bin). HOME=/root covers tooling that needs it (dockerd runs as root).
result = self.execute_in_task_filesystem(
"[ -x /usr/local/bin/bootstrap-dev-stack ] || exit 3; "
"docker_config=$(/usr/bin/mktemp -d /run/posthog-bootstrap-docker.XXXXXX) || exit 1; "
'/usr/bin/env -i HOME=/root DOCKER_CONFIG="$docker_config" '
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin "
"setsid /usr/local/bin/bootstrap-dev-stack >/var/log/bootstrap-dev-stack.log 2>&1 </dev/null &",
timeout_seconds=30,
)
except Exception as e:
_logger.warning("dev_stack_bootstrap_launch_failed", sandbox_id=self.id, error=str(e))
return False
if result.exit_code == 0:
return True
if result.exit_code != 3:
_logger.warning(
"dev_stack_bootstrap_launch_failed",
sandbox_id=self.id,
exit_code=result.exit_code,
stderr=result.stderr,
)
return False
def agent_server_supports_prewarmed_resume_message_driven(self) -> bool:
result = self.execute(
build_agent_server_capability_probe("prewarmed_resume_message_driven"), timeout_seconds=10
)
return result.exit_code == 0
def clone_repository(
self,
repository: str,
github_token: str | None = "",
shallow: bool = True,
branch: str | None = None,
blobless: bool = False,
) -> ExecutionResult:
if not self.is_running():
raise RuntimeError("Sandbox not in running state.")
org, repo = repository.lower().split("/")
repo_url = (
f"https://x-access-token:{github_token}@github.com/{org}/{repo}.git"
if github_token
else f"https://github.com/{org}/{repo}.git"
)
target_path = sandbox_repo_path(repository)
org_path = f"{SANDBOX_REPOSITORIES_ROOT}/{org}"
depth_flag = f" --depth {shlex.quote('1')}" if shallow else ""
branch_flag = f" --branch {shlex.quote(branch)}" if branch else ""
blob_filter = ""
if not shallow:
blob_filter = " --filter=blob:none" if blobless else " --filter=blob:limit=128k"
clone_command = (
f"rm -rf {shlex.quote(target_path)} && "
f"mkdir -p {shlex.quote(org_path)} && "
f"cd {shlex.quote(org_path)} && "
f"git clone --single-branch{blob_filter}{depth_flag}{branch_flag} "
f"{shlex.quote(repo_url)} {shlex.quote(repo)}"
)
_logger.info(f"Cloning repository {repository} to {target_path} in sandbox {self.id} (shallow={shallow})")
return self.execute(clone_command, timeout_seconds=5 * 60)
@abstractmethod
def setup_repository(self, repository: str) -> ExecutionResult: ...
@abstractmethod
def is_git_clean(self, repository: str) -> tuple[bool, str]: ...
@abstractmethod
def execute_task(
self,
task_id: str,
run_id: str,
repository: str | None = None,
create_pr: bool = True,
) -> ExecutionResult: ...
@abstractmethod
def get_connect_credentials(self) -> AgentServerResult:
"""Get connect credentials (URL and token) for this sandbox.
Should be called after sandbox creation to get the URL and authentication
token needed to connect to the sandbox.
"""
...
@abstractmethod
def create_preview_connect_credentials(self, port: int, user_metadata: dict[str, Any]) -> AgentServerResult: ...
@abstractmethod
def start_agent_server(
self,
repository: str | None,
task_id: str,
run_id: str,
mode: str = "background",
create_pr: bool = True,
auto_publish: bool = False,
interaction_origin: str | None = None,
branch: str | None = None,
agent_runtime: str | None = None,
runtime_adapter: str | None = None,
provider: str | None = None,
model: str | None = None,
reasoning_effort: str | None = None,
service_tier: str | None = None,
context_window: str | None = None,
fast_mode: bool | None = None,
initial_permission_mode: str | None = None,
mcp_configs: list[McpServerConfig] | None = None,
relayed_mcp_servers: list[str] | None = None,
allowed_domains: list[str] | None = None,
event_ingest_token: str | None = None,
task_run_session_token: str | None = None,
event_ingest_url: str | None = None,
repo_ready_file: str | None = None,
wait_for_health: bool = True,
rtk_enabled: bool = True,
benjamin_enabled: bool = False,
pi_acp_conversation: bool = False,
claude_model_access: str | None = None,
codex_model_access: str | None = None,
codex_run_token: str | None = None,
sandbox_runtime: str | None = None,
before_launch: Callable[[], None] | None = None,
) -> int | None:
"""Start the agent-server HTTP server in the sandbox.
The sandbox URL and token should be obtained via get_connect_credentials()
before calling this method.
"""
...
def supports_combined_agent_server_start_and_health(self) -> bool:
return False
@abstractmethod
def wait_for_agent_server_ready(
self, allowed_domains: list[str] | None = None, *, claude_model_access: str | None = None
) -> None: ...
@abstractmethod
def mark_repo_ready(self, repo_ready_file: str) -> None: ...
@abstractmethod
def create_snapshot(self, *, timeout_seconds: int | None = None) -> str: ...
@abstractmethod
def create_directory_snapshot(self, path: str) -> str: ...
@abstractmethod
def prune_snapshot_heavy_dirs(self, path: str) -> None: ...
@abstractmethod
def destroy(self) -> None: ...
@abstractmethod
def is_running(self) -> bool: ...
def exit_reason(self) -> str | None:
return None
def exit_status(self) -> str | None:
return None
def read_agent_server_session_init_ms(self) -> int | None:
return None
def read_agent_server_boot_phases_ms(self) -> dict[str, int]:
return {}
def read_agent_server_boot_metrics(self) -> tuple[int | None, dict[str, int]]:
return None, {}
def agent_server_health_url(self) -> str:
return "http://127.0.0.1:8080/health"
def read_cpu_usage_usec(self) -> int | None:
return None
def start_cpu_billing_sampler(self) -> bool:
return False
def read_billed_cpu_usage_usec(self) -> int | None:
return None
def _read_health_session_init_ms(self, port: int) -> int | None:
try:
result = self.execute(f"curl -s --max-time 5 http://localhost:{port}/health", timeout_seconds=10)
payload = json.loads(result.stdout or "{}")
session_init_ms = payload.get("sessionInitMs")
return int(session_init_ms) if isinstance(session_init_ms, int | float) else None
except Exception:
return None
def _read_health_boot_metrics(self, port: int) -> tuple[int | None, dict[str, int]]:
try:
result = self.execute(f"curl -s --max-time 5 http://localhost:{port}/health", timeout_seconds=10)
payload = json.loads(result.stdout or "{}")
session_init_ms = payload.get("sessionInitMs")
boot = payload.get("boot", {})
raw_phases = boot.get("phasesMs", {}) if isinstance(boot, dict) else {}
allowed_phases = {
"context_fetch",
"acp_initialize",
"repository_ready",
"session_dependencies",
"session_create",
}
phases = (
{
phase: max(0, int(duration))
for phase, duration in raw_phases.items()
if phase in allowed_phases and isinstance(duration, int | float)
}
if isinstance(raw_phases, dict)
else {}
)
versioned_contract = isinstance(boot, dict) and "contractVersion" in boot
for source, target in (
("totalMs", "server_total"),
("httpReadyMs", "http_ready"),
("launcherToProcessMs", "launcher_to_process"),
):
if source == "totalMs" and not versioned_contract:
continue
duration = boot.get(source) if isinstance(boot, dict) else None
if isinstance(duration, int | float) and not isinstance(duration, bool):
phases[target] = max(0, int(duration))
boot_ms = payload.get("bootMs")
if isinstance(boot_ms, int | float) and not isinstance(boot_ms, bool):
phases["process_total"] = max(0, int(boot_ms))
return int(session_init_ms) if isinstance(session_init_ms, int | float) else None, phases
except Exception:
return None, {}
def _read_health_boot_phases_ms(self, port: int) -> dict[str, int]:
try:
result = self.execute(f"curl -s --max-time 5 http://localhost:{port}/health", timeout_seconds=10)
payload = json.loads(result.stdout or "{}")
raw_phases = payload.get("boot", {}).get("phasesMs", {})
allowed_phases = {
"context_fetch",
"acp_initialize",
"repository_ready",
"session_dependencies",
"session_create",
}
if not isinstance(raw_phases, dict):
return {}
return {
phase: max(0, int(duration))
for phase, duration in raw_phases.items()
if phase in allowed_phases and isinstance(duration, int | float)
}
except Exception:
return {}
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.destroy()
_ExecuteFn = Callable[..., ExecutionResult]
_logger = structlog.get_logger(__name__)
def parse_sandbox_repo_mount_map() -> dict[str, str]:
"""Parse SANDBOX_REPO_MOUNT_MAP into {lower(org/repo): expanded_local_path}.
Used by Docker sandbox for bind mounts and by task activities for user-facing logs.
Format: ``org/repo:/local/path,org2/repo2:~/other/path``
"""
raw = os.environ.get("SANDBOX_REPO_MOUNT_MAP", "")
if not raw:
return {}
result: dict[str, str] = {}
for entry in raw.split(","):
entry = entry.strip()
if not entry:
continue
parts = entry.split(":", 1)
if len(parts) != 2 or "/" not in parts[0]:
_logger.warning(f"Ignoring malformed SANDBOX_REPO_MOUNT_MAP entry: {entry}")
continue
repo_key = parts[0].strip().lower()
local_path = os.path.expanduser(parts[1].strip())
if not os.path.isdir(local_path):
_logger.warning(f"SANDBOX_REPO_MOUNT_MAP: path does not exist, skipping: {local_path}")
continue
result[repo_key] = os.path.abspath(local_path)
return result
CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE = (
"This run could not get a ChatGPT token from PostHog. Start the task again. "
"If it keeps failing, connect your ChatGPT account again in Settings > Harness."
)
# Named for the same reason as the Codex message above, and worded for whoever is actually
# listening. PostHog Desktop is no longer the only client that can answer a credential
# request — an API caller relays the token itself — so telling everyone to "open Desktop"
# leaves those callers with no way to act on the one error that ends their run.
CLAUDE_CREDENTIAL_UNAVAILABLE_MESSAGE = (
"The Claude token did not arrive. Whoever started this run has to answer its "
"credential_request within 120 seconds: PostHog Desktop answers from Settings > Harness, "
"and an API caller relays the token to the run's command endpoint. Then start the task again."
)
# The agent-server option each adapter's own-subscription runs need. The launcher greps the
# binary for it before it starts a run, so both uses read the same name.
SUBSCRIPTION_CLI_FLAGS = {"claude": "--claudeSubscription", "codex": "--codexSubscription"}
def build_subscription_flags(claude_model_access: str | None, codex_model_access: str | None) -> str:
access = {"claude": claude_model_access, "codex": codex_model_access}
return "".join(
f" {flag}" for adapter, flag in SUBSCRIPTION_CLI_FLAGS.items() if access[adapter] == "own-subscription"
)
def wait_for_health_check(
execute: _ExecuteFn,
sandbox_id: str,
port: int,
max_attempts: int = 60,
poll_interval: float = 0.5,
pid_file: str | None = None,
) -> bool:
"""Poll health endpoint until server is ready (single remote call).
Runs a bash polling loop inside the sandbox so only one round-trip is
needed regardless of how many attempts are required.
"""
health_script = build_health_check_command(port, max_attempts, poll_interval, pid_file)
result = execute(health_script, timeout_seconds=health_check_timeout_seconds(max_attempts, poll_interval))
if result.exit_code != 0:
raise_startup_failure(result.stdout, sandbox_id)
if "claude_credential_unavailable" in result.stdout:
from products.tasks.backend.exceptions import ProcessTaskFatalError
raise ProcessTaskFatalError(
CLAUDE_CREDENTIAL_UNAVAILABLE_MESSAGE,
{"sandbox_id": sandbox_id},
RuntimeError("Claude token unavailable"),
capture=False,
)
if "codex_credential_unavailable" in result.stdout:
from products.tasks.backend.exceptions import ProcessTaskFatalError
raise ProcessTaskFatalError(
CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE,
{"sandbox_id": sandbox_id},
RuntimeError("ChatGPT token unavailable"),
capture=False,
)
if result.exit_code == 0:
_logger.info(f"Agent-server health check passed in sandbox {sandbox_id} ({result.stdout.strip()})")
return True
return False
HEALTH_CURL_MAX_TIME_SECONDS = 2
SETUP_HOOKS_BUDGET_SECONDS = 630
def build_health_check_command(
port: int, max_attempts: int = 60, poll_interval: float = 0.5, pid_file: str | None = None
) -> str:
process_check = (
f'if [ -f {shlex.quote(pid_file)} ]; then kill -0 "$(cat {shlex.quote(pid_file)})" 2>/dev/null || exit 1; fi; '
if pid_file is not None
else ""
)
# The attempt count assumes an instant poll. A poll that waits on curl or python startup
# would otherwise outrun the exec timeout, and the caller never sees the loop's result.
budget_seconds = health_check_budget_seconds(max_attempts, poll_interval)
hooks_budget_seconds = max(budget_seconds, SETUP_HOOKS_BUDGET_SECONDS)
hooks_max_attempts = max(max_attempts, int(hooks_budget_seconds / poll_interval) if poll_interval > 0 else 0)
return (
f"SECONDS=0; i=0; max_attempts={max_attempts}; budget={budget_seconds}; while :; do "
" i=$((i + 1)); "
f"{process_check}"
f" body=$(curl -q -s --max-time {HEALTH_CURL_MAX_TIME_SECONDS} http://localhost:{port}/health); "
" status=$?; "
' if [ "$status" = "0" ]; then '
" python3 -c '"
"import json, sys; "
"payload = json.loads(sys.argv[1]); "
'ready = payload.get("status") == "ok" and payload.get("hasSession") is True; '
'sys.exit(0 if ready else 3 if payload.get("readiness") == "failed" '
'else 2 if payload.get("initializationPhase") == "setup_hooks" else 1)'
'\' "$body"; ready=$?; '
' if [ "$ready" = "0" ]; then echo "ok:$i"; exit 0; fi; '
' if [ "$ready" = "3" ]; then printf "%s\\n" "$body"; exit 1; fi; '
' case "$body" in *claude_credential_unavailable*) echo "claude_credential_unavailable"; exit 1;; '
'*codex_credential_unavailable*) echo "codex_credential_unavailable"; exit 1;; esac; '
f' if [ "$ready" = "2" ]; then max_attempts={hooks_max_attempts}; budget={hooks_budget_seconds}; fi; '
" fi; "
' if [ "$i" -ge "$max_attempts" ] || [ "$SECONDS" -ge "$budget" ]; then exit 1; fi; '
f" sleep {poll_interval}; "
"done"
)
def health_check_budget_seconds(max_attempts: int = 60, poll_interval: float = 0.5) -> int:
return int(max_attempts * poll_interval)
def health_check_timeout_seconds(max_attempts: int = 60, poll_interval: float = 0.5) -> int:
budget_seconds = max(health_check_budget_seconds(max_attempts, poll_interval), SETUP_HOOKS_BUDGET_SECONDS)
return max(30, budget_seconds + HEALTH_CURL_MAX_TIME_SECONDS + 5)
SandboxClass = type[SandboxBase]
def _get_docker_sandbox_class() -> SandboxClass:
# Allow TEST too: the guard runs at module import, and pytest loads settings with
# DEBUG off in some paths — blocking there would kill collection, not production.
if not (settings.DEBUG or settings.TEST):
raise RuntimeError(
"DockerSandbox is for local development only. Set DEBUG=1 (the flox env sets this "
"automatically — are you outside 'flox activate'?) or unset SANDBOX_PROVIDER "
"(check .env/.env.local and your shell)."
)
from .docker_sandbox import DockerSandbox
return DockerSandbox
def _get_modal_docker_sandbox_class() -> SandboxClass:
"""Modal sandbox with a separate app name for local development.
Uses a dedicated Modal app (posthog-sandbox-modal-docker-*) so that
local image builds with LOCAL_POSTHOG_CODE_MONOREPO_ROOT don't
pollute the production app's image cache.
"""
# Allow TEST too: the guard runs at module import, and pytest loads settings with
# DEBUG off in some paths — blocking there would kill collection, not production.
if not (settings.DEBUG or settings.TEST):
raise RuntimeError(
"MODAL_DOCKER sandbox is for local development only. Set DEBUG=1 (the flox env sets "
"this automatically — are you outside 'flox activate'?) or unset SANDBOX_PROVIDER "
"(check .env/.env.local and your shell)."
)
from .modal_sandbox import ModalSandbox
class ModalDockerSandbox(ModalSandbox):
DEFAULT_APP_NAME = "posthog-sandbox-modal-docker-default"
NOTEBOOK_APP_NAME = "posthog-sandbox-modal-docker-notebook"
STREAMLIT_APP_NAME = "posthog-sandbox-modal-docker-streamlit"
SELF_DRIVING_APP_NAME = "posthog-sandbox-modal-docker-self-driving"
return ModalDockerSandbox
def _get_modal_evals_sandbox_class() -> SandboxClass:
"""Modal sandbox isolated from both production and local development apps."""
if not (settings.DEBUG or settings.TEST):
raise RuntimeError("MODAL_EVALS sandbox is for evals only and requires DEBUG=1 or TEST=1.")
from .modal_sandbox import ModalSandbox
class ModalEvalsSandbox(ModalSandbox):
DEFAULT_APP_NAME = "posthog-sandbox-evals"
NOTEBOOK_APP_NAME = "posthog-sandbox-evals"
STREAMLIT_APP_NAME = "posthog-sandbox-evals"
# Evals are their own cost centre already — a self-driving eval stays in the evals app.
SELF_DRIVING_APP_NAME = "posthog-sandbox-evals"
return ModalEvalsSandbox
def _get_hogland_sandbox_class() -> SandboxClass:
from .hogland_sandbox import HoglandSandbox
return HoglandSandbox
def get_sandbox_class() -> SandboxClass:
provider = getattr(settings, "SANDBOX_PROVIDER", None)
if provider == "docker":
return _get_docker_sandbox_class()
if provider and provider.upper() == "MODAL_DOCKER":
return _get_modal_docker_sandbox_class()
if provider and provider.upper() == "MODAL_EVALS":
return _get_modal_evals_sandbox_class()
if provider and provider.lower() == "hogland":
# Global default only for local development — production routes per run via
# get_sandbox_class_for_backend, driven by the tasks-hogland-sandbox flag.
if not (settings.DEBUG or settings.TEST):
raise RuntimeError(
"SANDBOX_PROVIDER=hogland is for local development only. In production the "
"hogland backend is selected per run by the tasks-hogland-sandbox feature flag."
)
return _get_hogland_sandbox_class()
# Default to Modal everywhere
from .modal_sandbox import ModalSandbox
return ModalSandbox
def get_sandbox_class_for_backend(backend: str) -> SandboxClass:
if backend == "modal":
from .modal_sandbox import ModalSandbox
return ModalSandbox
if backend in ("modal_docker", "MODAL_DOCKER"):
return _get_modal_docker_sandbox_class()
if backend in ("modal_evals", "MODAL_EVALS"):
return _get_modal_evals_sandbox_class()
if backend == "docker":
return _get_docker_sandbox_class()
if backend == "hogland":
return _get_hogland_sandbox_class()
raise RuntimeError(f"Unsupported sandbox backend: {backend}")
def get_sandbox_class_for_run_backend(backend: str) -> SandboxClass:
"""Resolve the provider class for a run whose backend was chosen at context time.
Only ``"hogland"`` diverts from the process default. Every other value — including
the ``"modal"`` default — falls through to ``get_sandbox_class()`` so
``SANDBOX_PROVIDER`` still selects docker / modal-docker / modal-evals in dev, test,
and evals. Routing straight to ``get_sandbox_class_for_backend("modal")`` here would
force ModalSandbox even under ``SANDBOX_PROVIDER=docker``, breaking local runs.
"""
if backend == "hogland":
return _get_hogland_sandbox_class()
return get_sandbox_class()
# hogland mints `box-<12 hex>` (hogd enforces `^box-[0-9a-f]{12}$`); Modal object ids
# are `sb-...`. A box restored from a pen keeps a `box-` id, so this covers pens too.
HOGLAND_SANDBOX_ID_PREFIX = "box-"
def get_sandbox_class_for_sandbox_id(sandbox_id: str) -> SandboxClass:
"""Resolve the provider class for an existing sandbox from its id alone.
Hogland box ids are `box-...` and Modal object ids `sb-...`, so the prefix is enough
to route the ~20 `get_by_id` call sites that hold only a persisted sandbox id (the
reaper, cleanup, and snapshot activities have no other backend context). Anything
that is not a hogland id falls through to the process-wide provider, preserving the
docker/local-dev behavior.
Getting this prefix wrong fails closed to the wrong provider: a hogland id would
resolve to Modal, whose `get_by_id` raises `SandboxNotFoundError`, so cleanup and the
reaper would silently skip a real hogbox and leak it. The persisted `sandbox_backend`
(see get_task_processing_context) is the authoritative signal for behavioral branches;
this prefix is a routing convenience checked against hogland's enforced id shape.
"""
if sandbox_id.startswith(HOGLAND_SANDBOX_ID_PREFIX):
return _get_hogland_sandbox_class()
return get_sandbox_class()
if TYPE_CHECKING:
# Declared for type-checkers only; resolved at runtime by __getattr__ -> get_sandbox_class().
Sandbox: SandboxClass
else:
def __getattr__(name: str) -> object:
# Resolve `Sandbox` lazily. Computing it at import time calls get_sandbox_class(),
# which for the docker / local Modal providers imports a sibling module
# (docker_sandbox / modal_sandbox). When that sibling is the first of the pair to be
# imported (e.g. test_docker_sandbox.py imports docker_sandbox, which imports this
# module), the eager call reaches back into the still-initializing sibling and fails
# as a circular import. Deferring to first attribute access breaks the cycle.
if name == "Sandbox":
sandbox_class = get_sandbox_class()
globals()["Sandbox"] = sandbox_class # cache so later lookups skip __getattr__
return sandbox_class
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
__all__ = [
"AgentServerResult",
"Sandbox",
"SandboxConfig",
"SandboxStatus",
"SandboxTemplate",
"ExecutionResult",
"ExecutionStream",
"SANDBOX_TTL_SECONDS",
"SandboxBase",
"WORKING_DIR",
"parse_sandbox_repo_mount_map",
"sandbox_repo_path",
"get_sandbox_class",
"get_sandbox_class_for_backend",
"wait_for_health_check",
]