:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cloud-agent): refresh sandbox GitHub credentials mid-session (#60862)
Alessandro Pogliaghi9bd95a70a181
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 0b4dc2b108db..6ef53a5d08ca 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -57,6 +57,13 @@ TASKS_USE_MODAL_RESUME_SNAPSHOTS: bool = get_from_env(# fast.TASKS_INACTIVITY_TIMEOUT_SECONDS: int = get_from_env("TASKS_INACTIVITY_TIMEOUT_SECONDS", 0, type_cast=int)+# Override the delay before the first in-sandbox credential refresh (default 20+# minutes). Set this low (e.g. 30) for local testing so the refresh loop fires+# quickly instead of waiting out the GitHub token's lifetime.+TASKS_CREDENTIAL_REFRESH_INITIAL_DELAY_SECONDS: int = get_from_env(+ "TASKS_CREDENTIAL_REFRESH_INITIAL_DELAY_SECONDS", 0, type_cast=int+)+TEMPORAL_LOG_LEVEL_PRODUCE: str = os.getenv("TEMPORAL_LOG_LEVEL_PRODUCE", "DEBUG")TEMPORAL_EXTERNAL_LOGS_QUEUE_SIZE: int = get_from_env("TEMPORAL_EXTERNAL_LOGS_QUEUE_SIZE", 0, type_cast=int)diff --git a/products/tasks/backend/services/agent_command.py b/products/tasks/backend/services/agent_command.pyindex 7821adc3b5f3..543943480513 100644--- a/products/tasks/backend/services/agent_command.py+++ b/products/tasks/backend/services/agent_command.py@@ -283,6 +283,8 @@ def send_refresh_session(mcp_servers: list[dict[str, Any]],auth_token: str | None = None,timeout: int = REFRESH_TIMEOUT_SECONDS,+ refreshed_credentials: list[str] | None = None,+ authorship: str | None = None,) -> CommandResult:"""Push updated MCP server configs into a live sandbox agent-server.@@ -290,11 +292,23 @@ def send_refresh_session(resuming with the new ``mcpServers`` list (preserving conversationhistory). Must be dispatched between turns — the agent-server will replywith JSON-RPC error -32002 if a prompt is currently in flight.++ ``refreshed_credentials`` piggybacks on this channel to notify the+ agent-server which in-sandbox credentials (e.g. ``["github"]``) were just+ re-injected, purely so it can surface a debug log. A credentials-only+ notification (empty ``mcp_servers``) is logged and returns immediately on+ the agent-server side without rebuilding the session, so it is safe to send+ mid-turn."""+ params: dict[str, Any] = {"mcpServers": mcp_servers}+ if refreshed_credentials:+ params["refreshedCredentials"] = refreshed_credentials+ if authorship:+ params["authorship"] = authorshipreturn send_agent_command(task_run,method=REFRESH_SESSION_METHOD,- params={"mcpServers": mcp_servers},+ params=params,auth_token=auth_token,timeout=timeout,)diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.pyindex 407ad77bc89b..861f766a4987 100644--- a/products/tasks/backend/temporal/__init__.py+++ b/products/tasks/backend/temporal/__init__.py@@ -23,6 +23,7 @@ from .process_task.activities import (post_slack_update,prepare_sandbox_for_repository,read_sandbox_logs,+ refresh_sandbox_credentials,relay_sandbox_events,send_followup_to_sandbox,start_agent_server,@@ -46,6 +47,7 @@ ACTIVITIES = [prepare_sandbox_for_repository,create_sandbox_for_repository,inject_fresh_tokens_on_resume,+ refresh_sandbox_credentials,clone_repository_in_sandbox,checkout_branch_in_sandbox,get_sandbox_for_repository,diff --git a/products/tasks/backend/temporal/constants.py b/products/tasks/backend/temporal/constants.pyindex 32b767ff1458..b1f3d32f8105 100644--- a/products/tasks/backend/temporal/constants.py+++ b/products/tasks/backend/temporal/constants.py@@ -27,6 +27,13 @@ MAX_CI_REPETITIONS = 3# transient failures; this is the outer cap.RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT = timedelta(hours=24)+# Delay before the first in-sandbox credential refresh, and the fallback cadence+# when the refresh activity can't report a token-specific interval. Kept under+# the ~1h GitHub installation-token TTL so the in-sandbox copy never lapses; the+# activity returns a token-aware interval for subsequent refreshes. Override via+# TASKS_CREDENTIAL_REFRESH_INITIAL_DELAY_SECONDS for local testing.+CREDENTIAL_REFRESH_INITIAL_DELAY = timedelta(seconds=settings.TASKS_CREDENTIAL_REFRESH_INITIAL_DELAY_SECONDS or 20 * 60)+# Forwarding a queued user message into the sandbox uses a one-shot activity# bounded by this timeout (seconds, not timedelta — matches the existing wire# format).diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex 6ff87c91dd2f..2dcdfd779c5a 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -96,6 +96,7 @@ from products.tasks.backend.temporal.process_task.activities.update_task_run_staUpdateTaskRunStatusInput,update_task_run_status,)+from products.tasks.backend.temporal.process_task.credential_refresh import run_credential_refresh_loopfrom products.tasks.backend.temporal.utils import log_on_fail# Names of signals this workflow sends back to the TaskManagement parent. Kept@@ -361,6 +362,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):self._parent_workflow_id = input.parent_workflow_idself._slack_thread_context = input.slack_thread_contextself._sandbox_id_for_cleanup = None+ credential_refresh_task: asyncio.Task[None] | None = Nonetry:# Reap any orphaned sandbox left by a prior execution under this@@ -408,6 +410,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):relay_task = asyncio.ensure_future(self._relay_sandbox_events(agent_server_output, sandbox_id=sandbox_id))+ if self.context.has_github_credentials:+ credential_refresh_task = asyncio.ensure_future(run_credential_refresh_loop(self.context, sandbox_id))+if self._should_forward_pending_user_message():await self._forward_pending_user_message()@@ -535,6 +540,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):# route them to a fresh sandbox instead of waiting on us.self._shutting_down = True+ if credential_refresh_task is not None:+ await self._cancel_relay(credential_refresh_task)+cleanup_sandbox_id = sandbox_id or self._sandbox_id_for_cleanupif cleanup_sandbox_id:if self._context and self._context.mode == "interactive" and self._context.use_modal_resume_snapshots:diff --git a/products/tasks/backend/temporal/process_task/activities/__init__.py b/products/tasks/backend/temporal/process_task/activities/__init__.pyindex 41eacafca3bf..59df36aff938 100644--- a/products/tasks/backend/temporal/process_task/activities/__init__.py+++ b/products/tasks/backend/temporal/process_task/activities/__init__.py@@ -25,6 +25,11 @@ from .provision_sandbox import (prepare_sandbox_for_repository,)from .read_sandbox_logs import ReadSandboxLogsInput, read_sandbox_logs+from .refresh_sandbox_credentials import (+ RefreshSandboxCredentialsInput,+ RefreshSandboxCredentialsOutput,+ refresh_sandbox_credentials,+)from .relay_sandbox_events import RelaySandboxEventsInput, relay_sandbox_eventsfrom .send_followup_to_sandbox import SendFollowupToSandboxInput, send_followup_to_sandboxfrom .start_agent_server import StartAgentServerInput, StartAgentServerOutput, start_agent_server@@ -49,6 +54,8 @@ __all__ = ["PrepareSandboxForRepositoryInput","PrepareSandboxForRepositoryOutput","ReadSandboxLogsInput",+ "RefreshSandboxCredentialsInput",+ "RefreshSandboxCredentialsOutput","StartAgentServerInput","StartAgentServerOutput","TaskProcessingContext",@@ -70,6 +77,7 @@ __all__ = ["post_slack_update","prepare_sandbox_for_repository","read_sandbox_logs",+ "refresh_sandbox_credentials","start_agent_server","track_workflow_event","update_task_run_status",diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex eb5ed9149a92..b822cad97c0f 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -16,6 +16,7 @@ from products.tasks.backend.temporal.exceptions import GitHubAuthenticationErrorfrom products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_usagefrom products.tasks.backend.temporal.oauth import create_oauth_access_tokenfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution+from products.tasks.backend.temporal.process_task.sandbox_credentials import set_git_remote_tokenfrom products.tasks.backend.temporal.process_task.utils import (get_git_identity_env_vars,get_sandbox_api_url,@@ -503,34 +504,14 @@ def inject_fresh_tokens_on_resume(input: InjectFreshTokensOnResumeInput) -> Nonesandbox = Sandbox.get_by_id(input.sandbox_id)- if input.repository and github_token:- org, repo = input.repository.lower().split("/")- repo_path = f"/tmp/workspace/repos/{org}/{repo}"- # Guard on .git existing so we don't fail when the snapshot was- # taken before the repository was cloned (or was repo-less).- update_remote = (- f"if [ -d {shlex.quote(repo_path + '/.git')} ]; then "- f"cd {shlex.quote(repo_path)} && "- f"git remote set-url origin "- f"https://x-access-token:{shlex.quote(github_token)}@github.com/{shlex.quote(input.repository)}.git; "- f"fi"- )- remote_result = sandbox.execute(update_remote, timeout_seconds=30)- if remote_result.exit_code != 0:- logger.warning(- "Failed to refresh git remote URL on resume",- extra={- "sandbox_id": input.sandbox_id,- "repository": input.repository,- "stderr": remote_result.stderr,- },- )+ if github_token and input.repository:+ set_git_remote_token(sandbox, input.repository, github_token)- # start_agent_server rewrites ENV_FILE from the live process env before- # launching the agent. Pre-seeding it here means any agentsh-wrapped- # command that runs between sandbox resume and start_agent_server- # (diagnostics, branch checkout) sees the fresh tokens instead of the- # stale snapshot values.+ # Pre-seed the agentsh env file so any wrapped command that runs between+ # resume and start_agent_server (diagnostics, branch checkout) sees the+ # fresh tokens instead of the stale snapshot values. start_agent_server+ # re-dumps the full process env over this, so a partial overwrite is fine+ # here (unlike the mid-run refresh, which must preserve the live env).fresh_env_vars: dict[str, str] = {}if github_token:fresh_env_vars["GITHUB_TOKEN"] = github_tokendiff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.pynew file mode 100644index 000000000000..686d7e407709--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py@@ -0,0 +1,123 @@+from dataclasses import dataclass++from temporalio import activity++from posthog.temporal.common.logger import get_logger+from posthog.temporal.common.utils import asyncify++from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.services.agent_command import send_refresh_session+from products.tasks.backend.services.connection_token import create_sandbox_connection_token+from products.tasks.backend.services.sandbox import Sandbox+from products.tasks.backend.temporal.exceptions import TaskNotFoundError+from products.tasks.backend.temporal.observability import log_activity_execution, track_event+from products.tasks.backend.temporal.process_task.sandbox_credentials import (+ DEFAULT_REFRESH_INTERVAL_SECONDS,+ build_sandbox_credentials,+)++from .get_task_processing_context import TaskProcessingContext++logger = get_logger(__name__)+++def _notify_agent_server_of_refresh(ctx: TaskProcessingContext, task: Task, refreshed_kinds: list[str]) -> None:+ """Tell the running agent-server which credentials were re-injected so it logs them.+ This is best-effort since the sandbox may be unreachable, so a failure here never fails the refresh itself.+ """+ try:+ task_run = TaskRun.objects.get(id=ctx.run_id)+ auth_token = None+ created_by = task.created_by+ if created_by and created_by.id:+ distinct_id = created_by.distinct_id or f"user_{created_by.id}"+ auth_token = create_sandbox_connection_token(task_run, user_id=created_by.id, distinct_id=distinct_id)+ authorship = (ctx.state or {}).get("pr_authorship_mode")+ send_refresh_session(+ task_run, [], auth_token=auth_token, refreshed_credentials=refreshed_kinds, authorship=authorship+ )+ except Exception:+ logger.warning("sandbox_credentials_refresh_notify_failed", run_id=ctx.run_id, exc_info=True)+++@dataclass+class RefreshSandboxCredentialsInput:+ context: TaskProcessingContext+ sandbox_id: str+++@dataclass+class RefreshSandboxCredentialsOutput:+ # Seconds the workflow should wait before refreshing again — derived from the+ # shortest-lived credential so the loop tracks the tightest TTL.+ next_refresh_seconds: float+ refreshed_kinds: list[str]+++@asyncify+def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> RefreshSandboxCredentialsOutput:+ """Re-inject fresh credentials into a still-running sandbox.++ Best-effort per credential: a single credential failing (e.g. a transient+ token-mint error) is logged and skipped rather than failing the run, since+ the sandbox may still be doing useful non-git work. The returned interval+ drives the workflow's refresh cadence.+ """+ ctx = input.context++ with log_activity_execution(+ "refresh_sandbox_credentials",+ sandbox_id=input.sandbox_id,+ **ctx.to_log_context(),+ ):+ try:+ task = Task.objects.select_related("created_by", "github_integration", "github_user_integration").get(+ id=ctx.task_id+ )+ except Task.DoesNotExist as e:+ raise TaskNotFoundError(f"Task {ctx.task_id} not found", {"task_id": ctx.task_id}, cause=e)++ sandbox = Sandbox.get_by_id(input.sandbox_id)++ refreshed_kinds: list[str] = []+ next_refresh = DEFAULT_REFRESH_INTERVAL_SECONDS+ intervals: list[float] = []++ for credential in build_sandbox_credentials(ctx):+ try:+ outcome = credential.refresh(sandbox, ctx, task)+ except Exception:+ logger.warning(+ "sandbox_credential_refresh_failed",+ kind=credential.kind,+ sandbox_id=input.sandbox_id,+ run_id=ctx.run_id,+ exc_info=True,+ )+ continue+ intervals.append(outcome.next_refresh_seconds)+ if outcome.refreshed:+ refreshed_kinds.append(outcome.kind)++ if intervals:+ next_refresh = min(intervals)++ if refreshed_kinds:+ _notify_agent_server_of_refresh(ctx, task, refreshed_kinds)++ track_event(+ "sandbox_credentials_refreshed",+ distinct_id=ctx.distinct_id,+ properties={+ "run_id": ctx.run_id,+ "task_id": ctx.task_id,+ "sandbox_id": input.sandbox_id,+ "repository": ctx.repository,+ "refreshed_kinds": refreshed_kinds,+ "next_refresh_seconds": next_refresh,+ },+ groups={"organization": ctx.organization_id, "project": ctx.team_uuid},+ )++ return RefreshSandboxCredentialsOutput(next_refresh_seconds=next_refresh, refreshed_kinds=refreshed_kinds)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.pynew file mode 100644index 000000000000..648917ceceef--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py@@ -0,0 +1,76 @@+import pytest+from unittest.mock import MagicMock, patch++from asgiref.sync import async_to_sync++from products.tasks.backend.services.sandbox import ExecutionResult+from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (+ RefreshSandboxCredentialsInput,+ refresh_sandbox_credentials,+)+from products.tasks.backend.temporal.process_task.sandbox_credentials import DEFAULT_REFRESH_INTERVAL_SECONDS++[email protected]_db(transaction=True)+class TestRefreshSandboxCredentialsActivity:+ @pytest.fixture+ def sandbox(self):+ fake = MagicMock()+ fake.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)+ fake.write_file.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)+ return fake++ def test_refreshes_github_credentials_and_reports_interval(+ self, activity_environment, task_context, test_task, sandbox+ ):+ with (+ patch(+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",+ return_value=sandbox,+ ),+ patch(+ "products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",+ return_value="ghs_fresh",+ ),+ patch(+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"+ ) as track_event,+ ):+ output = async_to_sync(activity_environment.run)(+ refresh_sandbox_credentials,+ RefreshSandboxCredentialsInput(context=task_context, sandbox_id="sandbox-abc"),+ )++ assert output.refreshed_kinds == ["github"]+ assert output.next_refresh_seconds == 20 * 60++ # git remote rewrite + env-file read both ran against the sandbox.+ assert any("git remote set-url origin" in str(c.args[0]) for c in sandbox.execute.call_args_list)+ sandbox.write_file.assert_called_once()++ track_event.assert_called_once()+ event_name = track_event.call_args[0][0]+ assert event_name == "sandbox_credentials_refreshed"+ assert track_event.call_args.kwargs["properties"]["refreshed_kinds"] == ["github"]++ def test_credential_failure_is_non_fatal(self, activity_environment, task_context, test_task, sandbox):+ with (+ patch(+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",+ return_value=sandbox,+ ),+ patch(+ "products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",+ side_effect=RuntimeError("token mint failed"),+ ),+ patch("products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"),+ ):+ # Must not raise — a failed refresh should not kill the run.+ output = async_to_sync(activity_environment.run)(+ refresh_sandbox_credentials,+ RefreshSandboxCredentialsInput(context=task_context, sandbox_id="sandbox-abc"),+ )++ assert output.refreshed_kinds == []+ # All credentials failed -> no per-token interval, so fall back to the default cadence.+ assert output.next_refresh_seconds == DEFAULT_REFRESH_INTERVAL_SECONDSdiff --git a/products/tasks/backend/temporal/process_task/credential_refresh.py b/products/tasks/backend/temporal/process_task/credential_refresh.pynew file mode 100644index 000000000000..1ff3ce5d5d35--- /dev/null+++ b/products/tasks/backend/temporal/process_task/credential_refresh.py@@ -0,0 +1,36 @@+from datetime import timedelta++from temporalio import workflow+from temporalio.common import RetryPolicy++from products.tasks.backend.temporal.constants import CREDENTIAL_REFRESH_INITIAL_DELAY++from .activities.get_task_processing_context import TaskProcessingContext+from .activities.refresh_sandbox_credentials import RefreshSandboxCredentialsInput, refresh_sandbox_credentials+++async def run_credential_refresh_loop(context: TaskProcessingContext, sandbox_id: str) -> None:+ """Periodically re-inject fresh credentials into the running sandbox.++ Sandbox credentials (GitHub token; user *or* installation, per authorship)+ are frozen into ``.git/config`` and the agentsh env file at boot/resume and+ expire while the sandbox stays warm. This loop re-applies them in place on a+ token-aware cadence so ``git``/``gh`` auth never lapses mid-run. Runs+ concurrently with the agent and is cancelled on completion. Shared by the+ ``process_task`` and ``execute_sandbox`` workflows.+ """+ next_refresh_seconds = CREDENTIAL_REFRESH_INITIAL_DELAY.total_seconds()+ while True:+ await workflow.sleep(next_refresh_seconds)+ try:+ result = await workflow.execute_activity(+ refresh_sandbox_credentials,+ RefreshSandboxCredentialsInput(context=context, sandbox_id=sandbox_id),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ next_refresh_seconds = result.next_refresh_seconds+ except Exception as e:+ # Non-fatal: keep the run alive and retry on the default cadence.+ workflow.logger.warning(f"Sandbox credential refresh failed (non-fatal): {e}")+ next_refresh_seconds = CREDENTIAL_REFRESH_INITIAL_DELAY.total_seconds()diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.pynew file mode 100644index 000000000000..e6ae7047af38--- /dev/null+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py@@ -0,0 +1,181 @@+"""+Refresh long-lived credentials inside a running task sandbox.+This module re-resolves a fresh token and re-applies it in place.+"""++import shlex+import base64+import logging+from dataclasses import dataclass+from typing import TYPE_CHECKING, Protocol++from products.tasks.backend.models import Task+from products.tasks.backend.services.agentsh import ENV_FILE+from products.tasks.backend.temporal.process_task.utils import get_sandbox_github_token++if TYPE_CHECKING:+ from products.tasks.backend.services.sandbox import SandboxBase++ from .activities.get_task_processing_context import TaskProcessingContext++logger = logging.getLogger(__name__)++GITHUB_ENV_KEYS = ("GITHUB_TOKEN", "GH_TOKEN")++# GitHub App tokens are refreshed server-side at their half-life, so a freshly+# resolved token has at least ~half its TTL remaining. Refresh at half of that+# floor again to guarantee the in-sandbox copy never lapses during an active run.+# ghs_ = installation access token, ~1h TTL → refresh every 20 min+# ghu_ = user-to-server token, ~8h TTL → refresh every 2 h+_GITHUB_REFRESH_INTERVAL_BY_PREFIX: dict[str, float] = {+ "ghs_": 20 * 60,+ "ghu_": 2 * 60 * 60,+}+# Used before the first token is resolved, and for any unrecognized prefix —+# short enough to stay under the 1h installation-token floor.+DEFAULT_REFRESH_INTERVAL_SECONDS: float = 20 * 60+++def github_refresh_interval_seconds(token: str) -> float:+ for prefix, interval in _GITHUB_REFRESH_INTERVAL_BY_PREFIX.items():+ if token.startswith(prefix):+ return interval+ return DEFAULT_REFRESH_INTERVAL_SECONDS+++def set_git_remote_token(sandbox: "SandboxBase", repository: str, github_token: str) -> bool:+ """Rewrite ``origin``'s remote URL with a fresh ``x-access-token``.++ Takes effect immediately — git re-reads ``.git/config`` on every operation,+ so this fixes ``git fetch``/``push`` even mid-turn. Guards on ``.git`` so it+ no-ops when the snapshot predates the clone.+ """+ org, repo = repository.lower().split("/")+ repo_path = f"/tmp/workspace/repos/{org}/{repo}"+ update_remote = (+ f"if [ -d {shlex.quote(repo_path + '/.git')} ]; then "+ f"cd {shlex.quote(repo_path)} && "+ f"git remote set-url origin "+ f"https://x-access-token:{shlex.quote(github_token)}@github.com/{shlex.quote(repository)}.git; "+ f"fi"+ )+ result = sandbox.execute(update_remote, timeout_seconds=30)+ if result.exit_code != 0:+ logger.warning(+ "Failed to refresh git remote URL",+ extra={"sandbox_id": sandbox.id, "repository": repository, "stderr": result.stderr},+ )+ return False+ return True+++def update_sandbox_env_file(sandbox: "SandboxBase", updates: dict[str, str]) -> bool:+ """Replace specific keys in the agentsh env file, preserving all other entries.++ The env file is a NUL-delimited ``key=value`` list that the agentsh exec+ wrapper re-sources on every command, so updating it here propagates fresh+ tokens to the agent's subsequent ``gh``/``git`` invocations without a reboot.+ Read-modify-write (via base64 to survive NUL bytes) so we never clobber the+ rest of the captured environment.+ """+ if not updates:+ return True++ read = sandbox.execute(f"base64 -w0 {shlex.quote(ENV_FILE)} 2>/dev/null || true", timeout_seconds=30)+ existing: bytes = b""+ if read.exit_code == 0 and read.stdout.strip():+ try:+ existing = base64.b64decode(read.stdout.strip())+ except Exception:+ logger.warning("Could not decode existing sandbox env file; rewriting only the updated keys")+ existing = b""++ ordered_keys: list[str] = []+ values: dict[str, bytes] = {}+ for entry in existing.split(b"\x00"):+ if not entry:+ continue+ key_bytes, _, value_bytes = entry.partition(b"=")+ key = key_bytes.decode("utf-8", "replace")+ if key not in values:+ ordered_keys.append(key)+ values[key] = value_bytes++ for key, value in updates.items():+ if key not in values:+ ordered_keys.append(key)+ values[key] = value.encode("utf-8")++ payload = b"".join(f"{key}=".encode() + values[key] + b"\x00" for key in ordered_keys)+ write = sandbox.write_file(ENV_FILE, payload)+ if write.exit_code != 0:+ logger.warning(+ "Failed to refresh agentsh env file",+ extra={"sandbox_id": sandbox.id, "env_file": ENV_FILE, "stderr": write.stderr},+ )+ return False+ return True+++def apply_github_credentials_to_sandbox(sandbox: "SandboxBase", repository: str | None, github_token: str) -> None:+ """Re-inject a GitHub token into both places a running sandbox reads it from."""+ if repository:+ set_git_remote_token(sandbox, repository, github_token)+ update_sandbox_env_file(sandbox, dict.fromkeys(GITHUB_ENV_KEYS, github_token))+++@dataclass+class CredentialRefreshOutcome:+ kind: str+ refreshed: bool+ next_refresh_seconds: float+++class SandboxCredential(Protocol):+ """A long-lived secret that can be re-resolved and re-applied to a sandbox.++ Implementations own their own token resolution, sandbox application, and+ refresh cadence, so the refresh activity is agnostic to credential type.+ """++ kind: str++ def refresh(self, sandbox: "SandboxBase", ctx: "TaskProcessingContext", task: Task) -> CredentialRefreshOutcome: ...+++@dataclass+class GitHubSandboxCredential:+ """Refreshes the GitHub token (user *or* installation, per authorship)."""++ kind: str = "github"++ def refresh(self, sandbox: "SandboxBase", ctx: "TaskProcessingContext", task: Task) -> CredentialRefreshOutcome:+ if not ctx.has_github_credentials:+ return CredentialRefreshOutcome(+ self.kind, refreshed=False, next_refresh_seconds=DEFAULT_REFRESH_INTERVAL_SECONDS+ )++ token = get_sandbox_github_token(+ ctx.github_integration_id,+ run_id=ctx.run_id,+ state=ctx.state,+ task=task,+ github_user_integration_id=ctx.github_user_integration_id,+ repository=ctx.repository,+ )+ if not token:+ return CredentialRefreshOutcome(+ self.kind, refreshed=False, next_refresh_seconds=DEFAULT_REFRESH_INTERVAL_SECONDS+ )++ apply_github_credentials_to_sandbox(sandbox, ctx.repository, token)+ return CredentialRefreshOutcome(+ self.kind, refreshed=True, next_refresh_seconds=github_refresh_interval_seconds(token)+ )+++def build_sandbox_credentials(ctx: "TaskProcessingContext") -> list[SandboxCredential]:+ credentials: list[SandboxCredential] = []+ if ctx.has_github_credentials:+ credentials.append(GitHubSandboxCredential())+ return credentialsdiff --git a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.pynew file mode 100644index 000000000000..3981ddd5ab2e--- /dev/null+++ b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py@@ -0,0 +1,157 @@+import base64++import pytest+from unittest.mock import MagicMock, patch++from products.tasks.backend.services.sandbox import ExecutionResult+from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext+from products.tasks.backend.temporal.process_task.sandbox_credentials import (+ DEFAULT_REFRESH_INTERVAL_SECONDS,+ GitHubSandboxCredential,+ build_sandbox_credentials,+ github_refresh_interval_seconds,+ set_git_remote_token,+ update_sandbox_env_file,+)+++def _ok(stdout: str = "") -> ExecutionResult:+ return ExecutionResult(stdout=stdout, stderr="", exit_code=0)+++def _context(**overrides) -> TaskProcessingContext:+ defaults: dict = {+ "task_id": "task-id",+ "run_id": "run-id",+ "team_id": 1,+ "team_uuid": "team-uuid",+ "organization_id": "org-id",+ "github_integration_id": 123,+ "repository": "explore-science/paper-wizard-frontend",+ "distinct_id": "distinct",+ }+ defaults.update(overrides)+ return TaskProcessingContext(**defaults)+++class TestGithubRefreshInterval:+ @pytest.mark.parametrize(+ "token,expected",+ [+ ("ghs_installationtoken", 20 * 60),+ ("ghu_usertoken", 2 * 60 * 60),+ ("gho_oauthtoken", DEFAULT_REFRESH_INTERVAL_SECONDS),+ ("unknown", DEFAULT_REFRESH_INTERVAL_SECONDS),+ ],+ )+ def test_interval_is_keyed_off_token_prefix(self, token, expected):+ assert github_refresh_interval_seconds(token) == expected+++class TestSetGitRemoteToken:+ def test_rewrites_remote_with_fresh_token(self):+ sandbox = MagicMock()+ sandbox.execute.return_value = _ok()++ assert set_git_remote_token(sandbox, "explore-science/paper-wizard-frontend", "ghs_new") is True++ command = sandbox.execute.call_args[0][0]+ assert "git remote set-url origin" in command+ assert "x-access-token:ghs_new" in command+ assert "explore-science/paper-wizard-frontend" in command++ def test_returns_false_on_failure(self):+ sandbox = MagicMock()+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="not a git repo", exit_code=128)++ assert set_git_remote_token(sandbox, "owner/repo", "ghs_new") is False+++class TestUpdateSandboxEnvFile:+ def test_preserves_other_keys_and_replaces_updated_ones(self):+ sandbox = MagicMock()+ existing = b"PATH=/usr/bin\x00GITHUB_TOKEN=ghs_old\x00HOME=/root\x00"+ sandbox.execute.return_value = _ok(base64.b64encode(existing).decode())+ sandbox.write_file.return_value = _ok()++ assert update_sandbox_env_file(sandbox, {"GITHUB_TOKEN": "ghs_new", "GH_TOKEN": "ghs_new"}) is True++ _, payload = sandbox.write_file.call_args[0]+ entries = {e.split(b"=", 1)[0]: e.split(b"=", 1)[1] for e in payload.split(b"\x00") if e}+ # Untouched keys survive, updated key is replaced, new key is appended.+ assert entries[b"PATH"] == b"/usr/bin"+ assert entries[b"HOME"] == b"/root"+ assert entries[b"GITHUB_TOKEN"] == b"ghs_new"+ assert entries[b"GH_TOKEN"] == b"ghs_new"++ def test_noop_when_no_updates(self):+ sandbox = MagicMock()+ assert update_sandbox_env_file(sandbox, {}) is True+ sandbox.execute.assert_not_called()+ sandbox.write_file.assert_not_called()++ def test_writes_updates_when_env_file_absent(self):+ sandbox = MagicMock()+ # base64 of empty file (the `|| true` path yields empty stdout).+ sandbox.execute.return_value = _ok("")+ sandbox.write_file.return_value = _ok()++ assert update_sandbox_env_file(sandbox, {"GH_TOKEN": "ghs_new"}) is True++ _, payload = sandbox.write_file.call_args[0]+ assert payload == b"GH_TOKEN=ghs_new\x00"+++class TestGitHubSandboxCredential:+ def test_resolves_and_applies_token_and_reports_interval(self):+ sandbox = MagicMock()+ sandbox.execute.return_value = _ok("")+ sandbox.write_file.return_value = _ok()+ ctx = _context()++ with patch(+ "products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",+ return_value="ghs_resolved",+ ) as resolve:+ outcome = GitHubSandboxCredential().refresh(sandbox, ctx, MagicMock())++ resolve.assert_called_once()+ assert outcome.refreshed is True+ assert outcome.kind == "github"+ assert outcome.next_refresh_seconds == 20 * 60+ # git remote rewrite ran with the fresh token.+ assert any("x-access-token:ghs_resolved" in str(c.args[0]) for c in sandbox.execute.call_args_list)+ sandbox.write_file.assert_called_once()++ def test_user_token_reports_longer_interval(self):+ sandbox = MagicMock()+ sandbox.execute.return_value = _ok("")+ sandbox.write_file.return_value = _ok()++ with patch(+ "products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",+ return_value="ghu_resolved",+ ):+ outcome = GitHubSandboxCredential().refresh(sandbox, _context(), MagicMock())++ assert outcome.next_refresh_seconds == 2 * 60 * 60++ def test_no_op_without_github_credentials(self):+ sandbox = MagicMock()+ ctx = _context(github_integration_id=None, github_user_integration_id=None)++ outcome = GitHubSandboxCredential().refresh(sandbox, ctx, MagicMock())++ assert outcome.refreshed is False+ sandbox.execute.assert_not_called()+ sandbox.write_file.assert_not_called()+++class TestBuildSandboxCredentials:+ def test_includes_github_when_credentials_present(self):+ credentials = build_sandbox_credentials(_context())+ assert [c.kind for c in credentials] == ["github"]++ def test_empty_without_github_credentials(self):+ ctx = _context(github_integration_id=None, github_user_integration_id=None)+ assert build_sandbox_credentials(ctx) == []diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 0da156da5b6e..8e8f4313684f 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -49,6 +49,7 @@ from .activities.send_followup_to_sandbox import SendFollowupToSandboxInput, senfrom .activities.start_agent_server import StartAgentServerInput, StartAgentServerOutput, start_agent_serverfrom .activities.track_workflow_event import TrackWorkflowEventInput, track_workflow_eventfrom .activities.update_task_run_status import UpdateTaskRunStatusInput, update_task_run_status+from .credential_refresh import run_credential_refresh_loop@dataclass@@ -357,6 +358,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):run_id = input.run_idself._sandbox_id_for_cleanup = Noneself._slack_thread_context = input.slack_thread_context+ credential_refresh_task: asyncio.Task[None] | None = Nonetry:self._context = await self._get_task_processing_context(input)self._posthog_mcp_scopes = input.posthog_mcp_scopes@@ -410,6 +412,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._relay_sandbox_events(agent_server_output, sandbox_id=sandbox_id))+ if self.context.has_github_credentials:+ credential_refresh_task = asyncio.ensure_future(run_credential_refresh_loop(self.context, sandbox_id))+if self._should_forward_pending_user_message():await self._forward_pending_user_message()@@ -576,6 +581,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):)finally:+ if credential_refresh_task is not None:+ await self._cancel_relay(credential_refresh_task)+cleanup_sandbox_id = sandbox_id or self._sandbox_id_for_cleanupif cleanup_sandbox_id:# When `use_modal_resume_snapshots` is off, resume relies on the