Skip to content

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

feat(cloud-agent): deliver refreshed token per command via BASH_ENV (#60863)

Alessandro Pogliaghic40ebe84cd5f
diff --git a/products/tasks/backend/services/agentsh.py b/products/tasks/backend/services/agentsh.py
index 020853f1d271..8f4aa91ffb18 100644
--- a/products/tasks/backend/services/agentsh.py
+++ b/products/tasks/backend/services/agentsh.py
@@ -9,6 +9,9 @@ AGENTSH_DAEMON_PORT = 18080
SESSION_ID_FILE = "/tmp/agentsh-session-id"
ENV_FILE = "/tmp/agent-env"
ENV_WRAPPER_SCRIPT = "/tmp/agentsh-env-wrapper.sh"
+# Sourced via BASH_ENV on every `bash -c` the agent runs, so git/gh pick up a
+# mid-session GitHub credential refresh (the backend rewrites ENV_FILE in place).
+BASH_ENV_SCRIPT = "/tmp/agentsh-bash-env.sh"
AGENTSH_AUDIT_DB = "/var/lib/agentsh/events.db"
INFRASTRUCTURE_DOMAINS = [
"*.posthog.com",
@@ -110,6 +113,19 @@ exec "$@"
"""
+def generate_bash_env_script() -> str:
+ """
+ Generate the script sourced via ``BASH_ENV``.
+ """
+ return f"""\
+while IFS= read -r -d $'\\0' kv 2>/dev/null; do
+ case "$kv" in
+ GH_TOKEN=*|GITHUB_TOKEN=*) export "$kv" ;;
+ esac
+done < {ENV_FILE} 2>/dev/null
+"""
+
+
def generate_config_yaml(*, enable_ptrace: bool = True, full_trace: bool = True) -> str:
sandbox: dict = {
"enabled": True,
diff --git a/products/tasks/backend/services/docker_sandbox.py b/products/tasks/backend/services/docker_sandbox.py
index 30d0d62b77e2..31a4cdba6868 100644
--- a/products/tasks/backend/services/docker_sandbox.py
+++ b/products/tasks/backend/services/docker_sandbox.py
@@ -29,11 +29,13 @@ from products.tasks.backend.temporal.exceptions import (
)
from .agentsh import (
+ BASH_ENV_SCRIPT,
ENV_FILE,
ENV_WRAPPER_SCRIPT,
SESSION_ID_FILE,
build_exec_prefix,
build_setup_script,
+ generate_bash_env_script,
generate_config_yaml,
generate_env_wrapper,
generate_policy_yaml,
@@ -654,7 +656,12 @@ class DockerSandbox(SandboxBase):
branch_flag = f" --baseBranch {shlex.quote(branch)}" if branch else ""
repo_flag = f" --repositoryPath {shlex.quote(repo_path)}" if repo_path else ""
domains_flag = f" --allowedDomains {shlex.quote(','.join(allowed_domains))}" if allowed_domains else ""
+ # Scope BASH_ENV to the agent-server process (not the container env) so only the
+ # agent's per-command tool shells re-source the refreshed token. Backend maintenance
+ # execs (clone/checkout/token injection) must not source it — the script could be
+ # persisted in a resume snapshot, so sourcing it from a backend exec is a trust hole.
server_cmd = (
+ f"env BASH_ENV={shlex.quote(BASH_ENV_SCRIPT)} "
f"{env_prefix}./node_modules/.bin/agent-server --port {AGENT_SERVER_PORT}{repo_flag} "
f"--taskId {shlex.quote(task_id)} --runId {shlex.quote(run_id)} --mode {shlex.quote(mode)}"
f"{create_pr_flag}{branch_flag}{mcp_servers_arg}{domains_flag}"
@@ -675,7 +682,9 @@ class DockerSandbox(SandboxBase):
f"{build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} &"
)
else:
- return f"cd /scripts && nohup {server_cmd} > /tmp/agent-server.log 2>&1 &"
+ # Write the env file even without agentsh so BASH_ENV (and the
+ # in-process token resolver) can re-read a backend-refreshed token.
+ return f"cd /scripts && env -0 > {ENV_FILE} && nohup {server_cmd} > /tmp/agent-server.log 2>&1 &"
def _launch_and_check(self, command: str) -> bool:
"""Execute the agent-server command and wait for the health check.
@@ -721,6 +730,12 @@ class DockerSandbox(SandboxBase):
org, repo = repository.lower().split("/")
repo_path = f"/tmp/workspace/repos/{org}/{repo}"
+ # The agent runs each tool command in a fresh shell; BASH_ENV re-sources
+ # the (backend-refreshed) GitHub token from the env file per command, so
+ # mid-session credential refreshes reach git/gh. Needed for both agentsh
+ # and non-agentsh runs.
+ self.write_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
+
if allowed_domains is not None:
self._setup_agentsh(WORKING_DIR, allowed_domains)
diff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/services/modal_sandbox.py
index 2fa3f78553cd..17e5983091cf 100644
--- a/products/tasks/backend/services/modal_sandbox.py
+++ b/products/tasks/backend/services/modal_sandbox.py
@@ -29,11 +29,13 @@ from posthog.settings import CLOUD_DEPLOYMENT
from products.tasks.backend.models import SandboxSnapshot
from products.tasks.backend.services.agentsh import (
+ BASH_ENV_SCRIPT,
ENV_FILE,
ENV_WRAPPER_SCRIPT,
SESSION_ID_FILE,
build_exec_prefix,
build_setup_script,
+ generate_bash_env_script,
generate_config_yaml,
generate_env_wrapper,
generate_policy_yaml,
@@ -619,7 +621,12 @@ class ModalSandbox(SandboxBase):
repo_flag = f" --repositoryPath {shlex.quote(repo_path)}" if repo_path else ""
branch_flag = f" --baseBranch {shlex.quote(branch)}" if branch else ""
domains_flag = f" --allowedDomains {shlex.quote(','.join(allowed_domains))}" if allowed_domains else ""
+ # Scope BASH_ENV to the agent-server process (not the container env) so only the
+ # agent's per-command tool shells re-source the refreshed token. Backend maintenance
+ # execs (clone/checkout/token injection) must not source it — the script could be
+ # persisted in a resume snapshot, so sourcing it from a backend exec is a trust hole.
server_cmd = (
+ f"env BASH_ENV={shlex.quote(BASH_ENV_SCRIPT)} "
f"{env_prefix}./node_modules/.bin/agent-server --port {AGENT_SERVER_PORT}{repo_flag} "
f"--taskId {shlex.quote(task_id)} --runId {shlex.quote(run_id)} --mode {shlex.quote(mode)}"
f"{create_pr_flag}{branch_flag}{mcp_servers_arg}{domains_flag}"
@@ -633,7 +640,7 @@ class ModalSandbox(SandboxBase):
f"{build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} &"
)
else:
- return f"cd /scripts && nohup {server_cmd} > /tmp/agent-server.log 2>&1 &"
+ return f"cd /scripts && env -0 > {ENV_FILE} && nohup {server_cmd} > /tmp/agent-server.log 2>&1 &"
def _launch_and_check(self, command: str) -> bool:
result = self.execute(command, timeout_seconds=30)
@@ -673,6 +680,8 @@ class ModalSandbox(SandboxBase):
org, repo = repository.lower().split("/")
repo_path = f"/tmp/workspace/repos/{org}/{repo}"
+ self.write_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
+
if allowed_domains is not None:
self._setup_agentsh(WORKING_DIR, allowed_domains)
diff --git a/products/tasks/backend/services/test_docker_sandbox.py b/products/tasks/backend/services/test_docker_sandbox.py
index 458e8008ce30..25f46828580a 100644
--- a/products/tasks/backend/services/test_docker_sandbox.py
+++ b/products/tasks/backend/services/test_docker_sandbox.py
@@ -1,5 +1,6 @@
import os
import subprocess
+from typing import Any
import pytest
from unittest.mock import MagicMock, patch
@@ -17,6 +18,19 @@ from products.tasks.backend.services.sandbox import (
from products.tasks.backend.temporal.exceptions import SandboxExecutionError
+def _agent_server_launch_command(mock_execute: Any) -> str:
+ """Return the agent-server launch command among the execute calls.
+
+ start_agent_server writes the BASH_ENV script (extra execute calls) before
+ launching the server, so the launch is no longer the first execute call.
+ """
+ for call in mock_execute.call_args_list:
+ command = call.args[0]
+ if "./node_modules/.bin/agent-server" in command:
+ return command
+ raise AssertionError("agent-server launch command not found among execute calls")
+
+
def docker_available() -> bool:
try:
result = subprocess.run(["docker", "info"], capture_output=True, timeout=5)
@@ -267,7 +281,7 @@ class TestDockerSandboxUnit:
with patch.object(sandbox, "_wait_for_health_check", return_value=True):
sandbox.start_agent_server(repository, task_id, run_id, mode)
- command = mock_execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_execute)
org, repo = repository.lower().split("/")
repo_path = f"/tmp/workspace/repos/{org}/{repo}"
@@ -353,10 +367,7 @@ class TestDockerSandboxUnit:
with patch.object(sandbox, "is_running", return_value=True):
with patch.object(sandbox, "execute") as mock_execute:
- mock_execute.side_effect = [
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ mock_execute.return_value = ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None)
with patch.object(sandbox, "_setup_agentsh") as mock_setup_agentsh:
sandbox.start_agent_server(
"posthog/posthog",
@@ -366,7 +377,7 @@ class TestDockerSandboxUnit:
)
mock_setup_agentsh.assert_not_called()
- command = mock_execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_execute)
assert "--createPr true" in command
assert "agentsh exec" not in command
assert "nohup" in command
@@ -381,10 +392,7 @@ class TestDockerSandboxUnit:
with patch.object(sandbox, "is_running", return_value=True):
with patch.object(sandbox, "execute") as mock_execute:
- mock_execute.side_effect = [
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ mock_execute.return_value = ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None)
with patch.object(sandbox, "_setup_agentsh") as mock_setup_agentsh:
sandbox.start_agent_server(
"posthog/posthog",
@@ -395,7 +403,7 @@ class TestDockerSandboxUnit:
)
mock_setup_agentsh.assert_called_once_with("/tmp/workspace", ["example.com"])
- command = mock_execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_execute)
assert "--createPr true" in command
assert "--allowedDomains example.com" in command
assert "agentsh exec" in command
@@ -409,10 +417,7 @@ class TestDockerSandboxUnit:
with patch.object(sandbox, "is_running", return_value=True):
with patch.object(sandbox, "execute") as mock_execute:
- mock_execute.side_effect = [
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ mock_execute.return_value = ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None)
with patch.object(sandbox, "_setup_agentsh") as mock_setup_agentsh:
sandbox.start_agent_server(
"posthog/posthog",
@@ -423,7 +428,7 @@ class TestDockerSandboxUnit:
)
mock_setup_agentsh.assert_called_once_with("/tmp/workspace", [])
- command = mock_execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_execute)
assert "--allowedDomains" not in command
assert "agentsh exec" in command
@@ -472,10 +477,7 @@ class TestDockerSandboxUnit:
with patch.object(sandbox, "is_running", return_value=True):
with patch.object(sandbox, "execute") as mock_execute:
- mock_execute.side_effect = [
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ mock_execute.return_value = ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None)
sandbox.start_agent_server(
"posthog/posthog",
"task-123",
@@ -484,7 +486,7 @@ class TestDockerSandboxUnit:
create_pr=create_pr,
)
- command = mock_execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_execute)
assert expected_flag in command
def test_start_agent_server_includes_runtime_environment_variables(self):
@@ -496,10 +498,7 @@ class TestDockerSandboxUnit:
with patch.object(sandbox, "is_running", return_value=True):
with patch.object(sandbox, "execute") as mock_execute:
- mock_execute.side_effect = [
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ mock_execute.return_value = ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None)
sandbox.start_agent_server(
"posthog/posthog",
"task-123",
@@ -512,7 +511,7 @@ class TestDockerSandboxUnit:
event_ingest_token="ingest-token",
)
- command = mock_execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_execute)
assert "POSTHOG_CODE_RUNTIME_ADAPTER=codex" in command
assert "POSTHOG_CODE_PROVIDER=openai" in command
assert "POSTHOG_CODE_MODEL=gpt-5.3-codex" in command
diff --git a/products/tasks/backend/services/tests/test_modal_sandbox.py b/products/tasks/backend/services/tests/test_modal_sandbox.py
index fb5acb587b4a..571c07843713 100644
--- a/products/tasks/backend/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/services/tests/test_modal_sandbox.py
@@ -23,6 +23,19 @@ from products.tasks.backend.services.sandbox import AgentServerResult, Execution
from products.tasks.backend.temporal.exceptions import SandboxExecutionError, SandboxProvisionError
+def _agent_server_launch_command(mock_execute: Any) -> str:
+ """Return the agent-server launch command among the execute calls.
+
+ start_agent_server writes the BASH_ENV script (one execute call) before
+ launching the server, so the launch is no longer the first execute call.
+ """
+ for call in mock_execute.call_args_list:
+ command = call.args[0]
+ if "./node_modules/.bin/agent-server" in command:
+ return command
+ raise AssertionError("agent-server launch command not found among execute calls")
+
+
def _mock_token_response(status_code: int = 200, token: str | None = "test-token"):
resp = MagicMock()
resp.status_code = status_code
@@ -289,10 +302,7 @@ class TestModalSandboxAgentServer:
def test_start_agent_server_success_without_domains_skips_agentsh(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
- side_effect=[
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
with patch.object(mock_sandbox, "_setup_agentsh") as mock_setup:
@@ -304,8 +314,7 @@ class TestModalSandboxAgentServer:
)
mock_setup.assert_not_called()
- start_call = mock_sandbox.execute.call_args_list[0]
- command = start_call[0][0]
+ command = _agent_server_launch_command(mock_sandbox.execute)
import shlex
assert f"--port {AGENT_SERVER_PORT}" in command
@@ -319,10 +328,7 @@ class TestModalSandboxAgentServer:
def test_start_agent_server_wraps_with_agentsh_when_domains_provided(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
- side_effect=[
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
with patch.object(mock_sandbox, "_setup_agentsh") as mock_setup_agentsh:
@@ -338,7 +344,7 @@ class TestModalSandboxAgentServer:
"/tmp/workspace",
["example.com"],
)
- command = mock_sandbox.execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_sandbox.execute)
assert "--createPr true" in command
assert "agentsh exec --client-timeout 2h --timeout 2h" in command
assert "env -0 > /tmp/agent-env" in command
@@ -347,10 +353,7 @@ class TestModalSandboxAgentServer:
def test_start_agent_server_wraps_with_agentsh_when_domains_empty(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
- side_effect=[
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
with patch.object(mock_sandbox, "_setup_agentsh") as mock_setup_agentsh:
@@ -363,7 +366,7 @@ class TestModalSandboxAgentServer:
)
mock_setup_agentsh.assert_called_once_with("/tmp/workspace", [])
- command = mock_sandbox.execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_sandbox.execute)
assert "--allowedDomains" not in command
assert "agentsh exec --client-timeout 2h --timeout 2h" in command
assert "env -0 > /tmp/agent-env" in command
@@ -377,10 +380,7 @@ class TestModalSandboxAgentServer:
)
def test_start_agent_server_passes_create_pr_flag(self, mock_sandbox: Any, create_pr: bool, expected_flag: str):
mock_sandbox.execute = MagicMock(
- side_effect=[
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
with patch.object(mock_sandbox, "_setup_agentsh"):
@@ -392,15 +392,12 @@ class TestModalSandboxAgentServer:
create_pr=create_pr,
)
- command = mock_sandbox.execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_sandbox.execute)
assert expected_flag in command
def test_start_agent_server_includes_runtime_environment_variables(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
- side_effect=[
- ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
- ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
- ]
+ return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
mock_sandbox.start_agent_server(
@@ -415,7 +412,7 @@ class TestModalSandboxAgentServer:
event_ingest_token="ingest-token",
)
- command = mock_sandbox.execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_sandbox.execute)
assert "POSTHOG_CODE_RUNTIME_ADAPTER=codex" in command
assert "POSTHOG_CODE_PROVIDER=openai" in command
assert "POSTHOG_CODE_MODEL=gpt-5.3-codex" in command
@@ -649,7 +646,7 @@ class TestModalSandboxCommandEscaping:
with patch.object(sandbox, "_wait_for_health_check", return_value=True):
sandbox.start_agent_server(repository, task_id, run_id, mode)
- command = mock_execute.call_args_list[0][0][0]
+ command = _agent_server_launch_command(mock_execute)
org, repo = repository.lower().split("/")
repo_path = f"/tmp/workspace/repos/{org}/{repo}"
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index b822cad97c0f..55dfaa81746b 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -38,6 +38,7 @@ RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS = {
"GH_TOKEN",
"LLM_GATEWAY_URL",
"POSTHOG_RESUME_RUN_ID",
+ "BASH_ENV",
}
@@ -176,6 +177,11 @@ def _build_environment_variables(
environment_variables["GITHUB_TOKEN"] = github_token
environment_variables["GH_TOKEN"] = github_token
+ # BASH_ENV is intentionally NOT set in the container env: it's applied only to the
+ # agent-server launch (see `_build_agent_server_command`) so backend maintenance execs
+ # don't source a script that a resume snapshot could control. It stays in
+ # RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS so a user-supplied env var can't add it here.
+
if settings.SANDBOX_LLM_GATEWAY_URL:
environment_variables["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URL
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index 183c9cf535d6..8e1e09af372d 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -285,7 +285,9 @@ class TestModalSandboxAgentShWrapping(TestCase):
create_pr=True,
)
self.assertNotIn("agentsh exec --client-timeout 2h --timeout 2h", cmd)
- self.assertNotIn("env -0 > /tmp/agent-env", cmd)
+ # The env file is written at launch regardless of agentsh so the
+ # mid-session credential refresh can re-source the token per command.
+ self.assertIn("env -0 > /tmp/agent-env", cmd)
self.assertNotIn(ENV_WRAPPER_SCRIPT, cmd)
self.assertIn("nohup", cmd)