Skip to content

The agent that grows with you

fix(tools): lazily bring up sandbox for vision_analyze reads

PRATHAMESH756e87d43a5765
diff --git a/tests/tools/test_ensure_task_env.py b/tests/tools/test_ensure_task_env.py
new file mode 100644
index 00000000000..a968f569bfd
--- /dev/null
+++ b/tests/tools/test_ensure_task_env.py
@@ -0,0 +1,58 @@
+"""Unit tests for terminal_tool.ensure_task_env — the lazy sandbox bring-up
+used by vision_analyze so a session's first action can be an in-sandbox file
+read without a prior terminal command (issue #62825)."""
+
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import tools.terminal_tool as tt
+
+
+def _clear(*task_ids):
+ for task_id in task_ids:
+ tt._active_environments.pop(task_id, None)
+ tt._last_activity.pop(task_id, None)
+
+
+def test_local_backend_is_noop(monkeypatch):
+ """Local backend reads images host-side — no sandbox is created."""
+ monkeypatch.setenv("TERMINAL_ENV", "local")
+ with patch.object(tt, "_create_environment") as create:
+ assert tt.ensure_task_env("t-local") is None
+ create.assert_not_called()
+
+
+def test_non_local_creates_and_reuses(monkeypatch):
+ """A non-local backend with no active env creates one, caches it, and a
+ second call reuses the cache instead of spawning a duplicate."""
+ monkeypatch.setenv("TERMINAL_ENV", "ssh")
+ task_id = "t-ssh"
+ eff = tt._resolve_container_task_id(task_id)
+ _clear(eff, task_id)
+ fake = SimpleNamespace(execute=lambda *a, **k: {"returncode": 0, "output": ""})
+ try:
+ with patch.object(tt, "_create_environment", return_value=fake) as create:
+ assert tt.ensure_task_env(task_id) is fake
+ create.assert_called_once()
+ assert tt.get_active_env(task_id) is fake
+
+ # Already active -> no second creation.
+ assert tt.ensure_task_env(task_id) is fake
+ create.assert_called_once()
+ finally:
+ _clear(eff, task_id)
+
+
+def test_creation_failure_returns_none_and_caches_nothing(monkeypatch):
+ """A failed bring-up is best-effort: return None and leave no env cached so
+ the caller keeps its fail-closed path."""
+ monkeypatch.setenv("TERMINAL_ENV", "ssh")
+ task_id = "t-ssh-fail"
+ eff = tt._resolve_container_task_id(task_id)
+ _clear(eff, task_id)
+ try:
+ with patch.object(tt, "_create_environment", side_effect=RuntimeError("boom")):
+ assert tt.ensure_task_env(task_id) is None
+ assert tt.get_active_env(task_id) is None
+ finally:
+ _clear(eff, task_id)
diff --git a/tests/tools/test_image_source.py b/tests/tools/test_image_source.py
index 112dbc70372..58afca0092c 100644
--- a/tests/tools/test_image_source.py
+++ b/tests/tools/test_image_source.py
@@ -28,6 +28,16 @@ def _reload(monkeypatch, hermes_home: Path):
return isrc
[email protected](autouse=True)
+def _no_real_sandbox_bringup(monkeypatch):
+ """Neutralize the resolver's lazy sandbox bring-up (issue #62825) so unit
+ tests never spawn a real ssh/docker env. Patched on terminal_tool (which
+ _reload does not touch) and resolved at call time, so it survives the
+ per-test image_source reload. The bring-up tests override it."""
+ import tools.terminal_tool as tt
+ monkeypatch.setattr(tt, "ensure_task_env", lambda *a, **k: None)
+
+
class TestDataUrl:
@pytest.mark.asyncio
async def test_valid_data_url_resolves_to_bytes(self, tmp_path, monkeypatch):
@@ -270,3 +280,53 @@ class TestSvgNormalization:
path, mime, err = vt._normalize_to_supported_image(svg, "image/svg+xml")
assert path is None
assert "rasterizer" in err
+
+
+class TestLazySandboxBringUp:
+ """Issue #62825: under a non-local backend, the FIRST vision_analyze of a
+ session (before any terminal command) must bring the sandbox up itself
+ instead of failing with 'no active sandbox session'."""
+
+ @pytest.mark.asyncio
+ async def test_first_read_brings_up_sandbox_then_reads(self, tmp_path, monkeypatch):
+ isrc = _reload(monkeypatch, tmp_path / "hermes")
+ monkeypatch.setenv("TERMINAL_ENV", "ssh")
+
+ brought_up = []
+ fake_env = SimpleNamespace(
+ execute=lambda cmd, **kw: {"returncode": 0, "output": base64.b64encode(PNG).decode()}
+ )
+
+ def fake_ensure(task_id):
+ brought_up.append(task_id)
+
+ # Env is absent until the lazy bring-up runs, then available — exactly
+ # the SSH-handshake ordering the bug was about.
+ def fake_get_active(task_id):
+ return fake_env if brought_up else None
+
+ import tools.terminal_tool as tt
+ monkeypatch.setattr(tt, "ensure_task_env", fake_ensure)
+ monkeypatch.setattr(isrc, "_get_active_env", fake_get_active)
+
+ res = await isrc.resolve_image_source("/tmp/test.png", isrc.ResolveContext(task_id="t1"))
+
+ assert brought_up == ["t1"] # bring-up was triggered before the read
+ assert res.origin == "container"
+ assert res.data == PNG
+
+ @pytest.mark.asyncio
+ async def test_bringup_that_yields_no_env_still_fails_closed(self, tmp_path, monkeypatch):
+ """If the bring-up can't produce an env, the resolver still refuses
+ rather than falling back to a host read."""
+ isrc = _reload(monkeypatch, tmp_path / "hermes")
+ monkeypatch.setenv("TERMINAL_ENV", "ssh")
+ secret = tmp_path / "id_rsa"
+ secret.write_bytes(b"HOST-PRIVATE-KEY")
+
+ import tools.terminal_tool as tt
+ monkeypatch.setattr(tt, "ensure_task_env", lambda *_a, **_k: None)
+ monkeypatch.setattr(isrc, "_get_active_env", lambda *_a, **_k: None)
+
+ with pytest.raises(isrc.SourceNotFound):
+ await isrc.resolve_image_source(str(secret), isrc.ResolveContext(task_id="t1"))
diff --git a/tools/image_source.py b/tools/image_source.py
index d41d3103e9f..bd8aecbf2b8 100644
--- a/tools/image_source.py
+++ b/tools/image_source.py
@@ -282,6 +282,25 @@ def _get_active_env(task_id: Optional[str]):
return None
+def _ensure_container_env(task_id: Optional[str]) -> None:
+ """Lazily bring up the sandbox (SSH/Docker/…) before an in-sandbox read.
+
+ Unlike the terminal tool, vision never triggered environment creation, so a
+ session whose first action is ``vision_analyze`` on a container-only path
+ under a non-local backend found no active env and failed — until a terminal
+ command happened to create one (issue #62825). Best-effort: any failure just
+ leaves the env absent and the caller hits the existing fail-closed error.
+ """
+ if not task_id:
+ return
+ try:
+ from tools.terminal_tool import ensure_task_env
+
+ ensure_task_env(task_id)
+ except Exception:
+ pass
+
+
async def _resolve_container_fallback(
p: Path, ctx: ResolveContext, src: str, permitted: tuple = ("image",)
) -> ResolvedImage:
@@ -300,6 +319,11 @@ async def _resolve_container_fallback(
import asyncio
import shlex
+ # Bring the sandbox up on demand: without this, the first vision_analyze of
+ # a session (before any terminal command) has no active env to read from
+ # under a non-local backend (issue #62825).
+ _ensure_container_env(ctx.task_id)
+
env = _get_active_env(ctx.task_id)
if env is None:
raise SourceNotFound(
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 1103584cb0d..cb2634e324a 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -1600,6 +1600,48 @@ def _get_modal_backend_state(modal_mode: object | None) -> Dict[str, Any]:
)
+def _ssh_config_from_config(config: Dict[str, Any]) -> dict:
+ """Build the ``ssh_config`` dict passed to :func:`_create_environment`.
+
+ Shared by the terminal tool's own get-or-create path and the lazy
+ :func:`ensure_task_env` bring-up so both derive SSH connection settings
+ from the resolved config identically.
+ """
+ return {
+ "host": config.get("ssh_host", ""),
+ "user": config.get("ssh_user", ""),
+ "port": config.get("ssh_port", 22),
+ "key": config.get("ssh_key", ""),
+ "persistent": config.get("ssh_persistent", False),
+ }
+
+
+def _container_config_from_config(config: Dict[str, Any]) -> dict:
+ """Build the ``container_config`` dict passed to :func:`_create_environment`.
+
+ Shared by the terminal tool's own get-or-create path and the lazy
+ :func:`ensure_task_env` bring-up (see :func:`_ssh_config_from_config`).
+ """
+ return {
+ "container_cpu": config.get("container_cpu", 1),
+ "container_memory": config.get("container_memory", 5120),
+ "container_disk": config.get("container_disk", 51200),
+ "container_persistent": config.get("container_persistent", True),
+ "modal_mode": config.get("modal_mode", "auto"),
+ "vercel_runtime": config.get("vercel_runtime", ""),
+ "docker_volumes": config.get("docker_volumes", []),
+ "docker_mount_cwd_to_workspace": config.get("docker_mount_cwd_to_workspace", False),
+ "docker_forward_env": config.get("docker_forward_env", []),
+ "docker_env": config.get("docker_env", {}),
+ "docker_run_as_host_user": config.get("docker_run_as_host_user", False),
+ "docker_extra_args": config.get("docker_extra_args", []),
+ "docker_shm_size": config.get("docker_shm_size", "1g"),
+ "docker_network": config.get("docker_network", True),
+ "docker_persist_across_processes": config.get("docker_persist_across_processes", True),
+ "docker_orphan_reaper": config.get("docker_orphan_reaper", True),
+ }
+
+
def _create_environment(env_type: str, image: str, cwd: str, timeout: int,
ssh_config: dict = None, container_config: dict = None,
local_config: dict = None,
@@ -1874,6 +1916,90 @@ def get_active_env(task_id: str):
return _active_environments.get(lookup) or _active_environments.get(task_id)
+def ensure_task_env(task_id: Optional[str] = None):
+ """Lazily create and cache the sandbox env for *task_id* if none is active.
+
+ :func:`terminal_tool` creates the environment on the first terminal command,
+ but nothing else did — so under a non-local backend (ssh, docker, …) a
+ session whose first action is ``vision_analyze`` on a container-only path hit
+ "no active sandbox session" because the SSH/Docker handshake never ran
+ (issue #62825). vision reads such paths inside the sandbox (see
+ ``tools.image_source``), so it calls this to bring the env up on demand,
+ reusing the same creation machinery as the terminal tool.
+
+ No-op on the local backend (images are read host-side). Returns the env
+ instance, or ``None`` when local or when creation fails (best-effort: a
+ failure leaves the caller's fail-closed error path intact).
+ """
+ config = _get_env_config()
+ env_type = config["env_type"]
+ if env_type == "local":
+ return None
+
+ effective_task_id = _resolve_container_task_id(task_id)
+
+ # Fast path: already active — mirror terminal_tool and refresh activity.
+ existing = get_active_env(effective_task_id)
+ if existing is not None:
+ with _env_lock:
+ _last_activity[effective_task_id] = time.time()
+ return existing
+
+ overrides = resolve_task_overrides(task_id)
+ if env_type == "docker":
+ image = overrides.get("docker_image") or config["docker_image"]
+ elif env_type == "singularity":
+ image = overrides.get("singularity_image") or config["singularity_image"]
+ elif env_type == "modal":
+ image = overrides.get("modal_image") or config["modal_image"]
+ elif env_type == "daytona":
+ image = overrides.get("daytona_image") or config["daytona_image"]
+ else:
+ image = ""
+
+ _start_cleanup_thread()
+
+ # Per-task creation lock so a concurrent terminal_tool call and this helper
+ # don't each spawn a sandbox for the same task.
+ with _creation_locks_lock:
+ task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock())
+
+ with task_lock:
+ existing = get_active_env(effective_task_id)
+ if existing is not None:
+ return existing
+ try:
+ new_env = _create_environment(
+ env_type=env_type,
+ image=image,
+ cwd=config["cwd"],
+ timeout=config["timeout"],
+ ssh_config=_ssh_config_from_config(config) if env_type == "ssh" else None,
+ container_config=(
+ _container_config_from_config(config)
+ if env_type in _CONTAINER_BACKENDS else None
+ ),
+ local_config=None,
+ task_id=effective_task_id,
+ host_cwd=config.get("host_cwd"),
+ )
+ except Exception as exc: # noqa: BLE001 — best-effort bring-up
+ logger.warning(
+ "Lazy %s environment init failed for task %s: %s",
+ env_type, effective_task_id[:8], exc,
+ )
+ return None
+
+ with _env_lock:
+ _active_environments[effective_task_id] = new_env
+ _last_activity[effective_task_id] = time.time()
+ logger.info(
+ "%s environment lazily initialized for task %s",
+ env_type, effective_task_id[:8],
+ )
+ return new_env
+
+
def is_persistent_env(task_id: str) -> bool:
"""Return True if the active environment for task_id is configured for
cross-turn persistence (``persistent_filesystem=True``).
@@ -2423,36 +2549,11 @@ def terminal_tool(
_check_disk_usage_warning()
logger.info("Creating new %s environment for task %s...", env_type, effective_task_id[:8])
try:
- ssh_config = None
- if env_type == "ssh":
- ssh_config = {
- "host": config.get("ssh_host", ""),
- "user": config.get("ssh_user", ""),
- "port": config.get("ssh_port", 22),
- "key": config.get("ssh_key", ""),
- "persistent": config.get("ssh_persistent", False),
- }
-
- container_config = None
- if env_type in {"docker", "singularity", "modal", "daytona", "vercel_sandbox"}:
- container_config = {
- "container_cpu": config.get("container_cpu", 1),
- "container_memory": config.get("container_memory", 5120),
- "container_disk": config.get("container_disk", 51200),
- "container_persistent": config.get("container_persistent", True),
- "modal_mode": config.get("modal_mode", "auto"),
- "vercel_runtime": config.get("vercel_runtime", ""),
- "docker_volumes": config.get("docker_volumes", []),
- "docker_mount_cwd_to_workspace": config.get("docker_mount_cwd_to_workspace", False),
- "docker_forward_env": config.get("docker_forward_env", []),
- "docker_env": config.get("docker_env", {}),
- "docker_run_as_host_user": config.get("docker_run_as_host_user", False),
- "docker_extra_args": config.get("docker_extra_args", []),
- "docker_shm_size": config.get("docker_shm_size", "1g"),
- "docker_network": config.get("docker_network", True),
- "docker_persist_across_processes": config.get("docker_persist_across_processes", True),
- "docker_orphan_reaper": config.get("docker_orphan_reaper", True),
- }
+ ssh_config = _ssh_config_from_config(config) if env_type == "ssh" else None
+ container_config = (
+ _container_config_from_config(config)
+ if env_type in _CONTAINER_BACKENDS else None
+ )
local_config = None
if env_type == "local":