Skip to content

The agent that grows with you

refactor(tools): collapse result/snapshot helpers in vercel + managed_modal; tighten modal worker

Teknium54f33b74e8b0
diff --git a/tools/environments/managed_modal.py b/tools/environments/managed_modal.py
index c645c3272e7..f5b7af5fd77 100644
--- a/tools/environments/managed_modal.py
+++ b/tools/environments/managed_modal.py
@@ -23,10 +23,7 @@ from tools.managed_tool_gateway import resolve_managed_tool_gateway
logger = logging.getLogger(__name__)
_TERMINAL_EXEC_STATUSES = frozenset({"completed", "failed", "cancelled", "timeout"})
-_POLL_INTERVAL_SECONDS = 0.25
_CLIENT_TIMEOUT_GRACE_SECONDS = 10.0
-_INTERRUPT_OUTPUT = "[Command interrupted - Modal sandbox exec cancelled]"
-_ERROR_PREFIX = "Managed Modal exec failed"
def _request_timeout_env(name: str, default: float) -> float:
@@ -37,14 +34,10 @@ def _request_timeout_env(name: str, default: float) -> float:
return default
-def _result(output: str, returncode: int) -> dict:
+def _result(output: str, returncode: int = 1) -> dict:
return {"output": output, "returncode": returncode}
-def _error_result(output: str) -> dict:
- return _result(output, 1)
-
-
class ManagedModalEnvironment(BaseEnvironment):
"""Gateway-owned Modal sandbox with Hermes-compatible execute/cleanup."""
@@ -97,7 +90,7 @@ class ManagedModalEnvironment(BaseEnvironment):
try:
exec_id, immediate = self._start_exec(exec_command, cwd or self.cwd, timeout, stdin_data)
except Exception as exc:
- return _error_result(f"{_ERROR_PREFIX}: {exc}")
+ return _result(f"Managed Modal exec failed: {exc}")
if immediate is not None:
return immediate
deadline = time.monotonic() + timeout + _CLIENT_TIMEOUT_GRACE_SECONDS
@@ -106,11 +99,11 @@ class ManagedModalEnvironment(BaseEnvironment):
while True:
if is_interrupted():
self._cancel_exec(exec_id)
- return _result(_INTERRUPT_OUTPUT, 130)
+ return _result("[Command interrupted - Modal sandbox exec cancelled]", 130)
try:
result = self._poll_exec(exec_id)
except Exception as exc:
- return _error_result(f"{_ERROR_PREFIX}: {exc}")
+ return _result(f"Managed Modal exec failed: {exc}")
if result is not None:
return result
if time.monotonic() >= deadline:
@@ -123,7 +116,7 @@ class ManagedModalEnvironment(BaseEnvironment):
touch_activity_if_due(_activity_state, "modal command running")
except Exception:
pass
- time.sleep(_POLL_INTERVAL_SECONDS)
+ time.sleep(0.25)
def _result_from_body(self, body: dict) -> dict | None:
"""Final result dict if the exec body reports a terminal status, else ``None``."""
@@ -142,15 +135,15 @@ class ManagedModalEnvironment(BaseEnvironment):
try:
response = self._request("POST", f"/v1/sandboxes/{self._sandbox_id}/execs", json=payload, timeout=10)
except Exception as exc:
- return exec_id, _error_result(f"Managed Modal exec failed: {exc}")
+ return exec_id, _result(f"Managed Modal exec failed: {exc}")
if response.status_code >= 400:
- return exec_id, _error_result(self._format_error("Managed Modal exec failed", response))
+ return exec_id, _result(self._format_error("Managed Modal exec failed", response))
body = response.json()
final = self._result_from_body(body)
if final is not None:
return exec_id, final
if body.get("execId") != exec_id:
- return exec_id, _error_result("Managed Modal exec start did not return the expected exec id")
+ return exec_id, _result("Managed Modal exec start did not return the expected exec id")
return exec_id, None
def _poll_exec(self, exec_id: str) -> dict | None:
@@ -159,11 +152,11 @@ class ManagedModalEnvironment(BaseEnvironment):
"GET", f"/v1/sandboxes/{self._sandbox_id}/execs/{exec_id}",
timeout=(self._CONNECT_TIMEOUT_SECONDS, self._POLL_READ_TIMEOUT_SECONDS))
except Exception as exc:
- return _error_result(f"Managed Modal exec poll failed: {exc}")
+ return _result(f"Managed Modal exec poll failed: {exc}")
if status_response.status_code == 404:
- return _error_result("Managed Modal exec not found")
+ return _result("Managed Modal exec not found")
if status_response.status_code >= 400:
- return _error_result(self._format_error("Managed Modal exec poll failed", status_response))
+ return _result(self._format_error("Managed Modal exec poll failed", status_response))
return self._result_from_body(status_response.json())
def _cancel_exec(self, exec_id: str) -> None:
diff --git a/tools/environments/modal.py b/tools/environments/modal.py
index 00c164a28f4..85d63d0402f 100644
--- a/tools/environments/modal.py
+++ b/tools/environments/modal.py
@@ -99,22 +99,18 @@ class _AsyncWorker:
self._started = threading.Event()
def start(self):
- self._thread = threading.Thread(target=self._run_loop, daemon=True)
+ def _run_loop():
+ self._loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(self._loop)
+ self._started.set()
+ self._loop.run_forever()
+ self._thread = threading.Thread(target=_run_loop, daemon=True)
self._thread.start()
self._started.wait(timeout=30)
- def _run_loop(self):
- self._loop = asyncio.new_event_loop()
- asyncio.set_event_loop(self._loop)
- self._started.set()
- self._loop.run_forever()
-
def run_coroutine(self, coro, timeout=600):
from agent.async_utils import safe_schedule_threadsafe
- if self._loop is None or self._loop.is_closed():
- if asyncio.iscoroutine(coro):
- coro.close()
- raise RuntimeError("AsyncWorker loop is not running")
+ # safe_schedule_threadsafe closes the coroutine and returns None for a missing/closed loop.
future = safe_schedule_threadsafe(coro, self._loop)
if future is None:
raise RuntimeError("AsyncWorker loop is not running")
@@ -148,11 +144,10 @@ class ModalEnvironment(BaseEnvironment):
self._worker = _AsyncWorker()
self._sync_manager: FileSyncManager | None = None # initialized after sandbox creation
sandbox_kwargs = dict(modal_sandbox_kwargs or {})
- restored_snapshot_id, restored_from_legacy_key = None, False
- if self._persistent:
- restored_snapshot_id, restored_from_legacy_key = _get_snapshot_restore_candidate(self._task_id)
- if restored_snapshot_id:
- logger.info("Modal: restoring from snapshot %s", restored_snapshot_id[:20])
+ restored_snapshot_id, restored_from_legacy_key = (
+ _get_snapshot_restore_candidate(self._task_id) if self._persistent else (None, False))
+ if restored_snapshot_id:
+ logger.info("Modal: restoring from snapshot %s", restored_snapshot_id[:20])
ensure_lazy_dep("terminal.modal")
import modal as _modal
cred_mounts = []
@@ -215,10 +210,8 @@ class ModalEnvironment(BaseEnvironment):
def _modal_upload(self, host_path: str, remote_path: str) -> None:
"""Upload a single file via base64 piped through stdin."""
- b64 = base64.b64encode(Path(host_path).read_bytes()).decode("ascii")
- container_dir = str(Path(remote_path).parent)
- cmd = f"mkdir -p {shlex.quote(container_dir)} && base64 -d > {shlex.quote(remote_path)}"
- self._exec_with_stdin(cmd, b64, timeout=30)
+ cmd = f"mkdir -p {shlex.quote(str(Path(remote_path).parent))} && base64 -d > {shlex.quote(remote_path)}"
+ self._exec_with_stdin(cmd, base64.b64encode(Path(host_path).read_bytes()).decode("ascii"), timeout=30)
def _modal_bulk_upload(self, files: list[tuple[str, str]]) -> None:
"""Upload many files as one in-memory gzipped tar streamed through stdin
@@ -241,16 +234,13 @@ class ModalEnvironment(BaseEnvironment):
exit_code = await proc.wait.aio()
if exit_code != 0:
raise RuntimeError(f"Modal bulk download failed (exit {exit_code})")
- return data
- tar_bytes = self._worker.run_coroutine(_download(), timeout=120)
- dest.write_bytes(tar_bytes.encode() if isinstance(tar_bytes, str) else tar_bytes)
+ return data.encode() if isinstance(data, str) else data
+ dest.write_bytes(self._worker.run_coroutine(_download(), timeout=120))
def _modal_delete(self, remote_paths: list[str]) -> None:
"""Batch-delete remote files via exec."""
- rm_cmd = quoted_rm_command(remote_paths)
-
async def _rm():
- proc = await self._sandbox.exec.aio("bash", "-c", rm_cmd)
+ proc = await self._sandbox.exec.aio("bash", "-c", quoted_rm_command(remote_paths))
await proc.wait.aio()
self._worker.run_coroutine(_rm(), timeout=15)
@@ -272,10 +262,7 @@ class ModalEnvironment(BaseEnvironment):
stdout = _as_text(await process.stdout.read.aio())
stderr = _as_text(await process.stderr.read.aio())
exit_code = await process.wait.aio()
- output = stdout
- if stderr:
- output = f"{stdout}\n{stderr}" if stdout else stderr
- return output, exit_code
+ return "\n".join(part for part in (stdout, stderr) if part), exit_code
return worker.run_coroutine(_do(), timeout=timeout + 30)
return _ThreadedProcessHandle(exec_fn, cancel_fn=cancel)
@@ -288,12 +275,11 @@ class ModalEnvironment(BaseEnvironment):
self._sync_manager.sync_back()
if self._persistent:
async def _snapshot():
- img = await self._sandbox.snapshot_filesystem.aio()
- return img.object_id
+ return (await self._sandbox.snapshot_filesystem.aio()).object_id
try:
snapshot_id = self._worker.run_coroutine(_snapshot(), timeout=60)
except Exception:
- snapshot_id = None
+ snapshot_id = None # snapshot errors are non-fatal; the sandbox is still terminated
if snapshot_id:
try:
_store_direct_snapshot(self._task_id, snapshot_id)
diff --git a/tools/environments/ssh.py b/tools/environments/ssh.py
index e1974a6c68c..d6a1241b9b3 100644
--- a/tools/environments/ssh.py
+++ b/tools/environments/ssh.py
@@ -53,10 +53,9 @@ class SSHEnvironment(BaseEnvironment):
self.control_dir = Path(tempfile.gettempdir()) / "hermes-ssh"
self.control_dir.mkdir(parents=True, exist_ok=True)
- # Short, deterministic socket name: the full path must stay under macOS's
- # 104-byte sun_path limit (raw user@host:port + SSH's 16-byte random suffix
- # under a deep $TMPDIR exceeds it), and stability across reconnects keeps
- # ControlMaster reuse working.
+ # Short, deterministic socket name: the path must stay under macOS's 104-byte sun_path
+ # limit (raw user@host:port + SSH's 16-byte suffix under a deep $TMPDIR exceeds it), and
+ # stability across reconnects keeps ControlMaster reuse working.
_socket_id = hashlib.sha256(f"{user}@{host}:{port}".encode()).hexdigest()[:16]
self.control_socket = self.control_dir / f"{_socket_id}.sock"
_ensure_ssh_available()
@@ -121,8 +120,6 @@ class SSHEnvironment(BaseEnvironment):
return home
return "/root" if self.user == "root" else f"/home/{self.user}"
- # -- File sync (via FileSyncManager) --------------------------------
-
def _ensure_remote_dirs(self) -> None:
"""Create base ~/.hermes directory tree on remote in one SSH call."""
base = f"{self._remote_home}/.hermes"
@@ -139,11 +136,8 @@ class SSHEnvironment(BaseEnvironment):
raise _sync_error(f"scp failed: {result.stderr.strip()}", f"File sync to {self.user}@{self.host}")
def _ssh_bulk_upload(self, files: list[tuple[str, str]]) -> None:
- """Upload many files in a single tar-over-SSH stream.
-
- Local ``tar c`` is piped through one SSH connection to remote ``tar x``;
- directory creation is batched into a single ``mkdir -p`` beforehand.
- """
+ """Upload many files in one tar-over-SSH stream: local ``tar c`` piped through one SSH
+ connection to remote ``tar x``, after a single batched ``mkdir -p``."""
if not files:
return
base = f"{self._remote_home}/.hermes"
@@ -230,8 +224,6 @@ class SSHEnvironment(BaseEnvironment):
"""Sync files to remote via FileSyncManager (rate-limited internally)."""
self._sync_manager.sync()
- # -- Execution ------------------------------------------------------
-
def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,
stdin_data: str | None = None) -> subprocess.Popen:
"""Spawn an SSH process that runs bash on the remote host."""
diff --git a/tools/environments/vercel_sandbox.py b/tools/environments/vercel_sandbox.py
index 70463fc5e26..e0a2ebc8cc0 100644
--- a/tools/environments/vercel_sandbox.py
+++ b/tools/environments/vercel_sandbox.py
@@ -41,9 +41,8 @@ _SNAPSHOT_STORE_NAME = "vercel_sandbox_snapshots.json"
def _ensure_vercel_sdk() -> None:
"""Lazy-install vercel SDK on demand. Idempotent."""
- # The vercel SDK (>=0.7) ships default-on usage telemetry. Hermes policy is no
- # outbound telemetry without explicit opt-in, so disable it before the SDK is
- # ever imported. Only the default is set — an explicit user value is never overridden.
+ # The SDK (>=0.7) ships default-on telemetry; Hermes policy is opt-in only, so disable it
+ # before the SDK is imported. setdefault: an explicit user value is never overridden.
os.environ.setdefault("VERCEL_TELEMETRY_DISABLED", "1")
ensure_lazy_dep("terminal.vercel")
@@ -76,60 +75,40 @@ def _retry_vercel_call(label: str, callback, *, attempts: int):
time.sleep(0.1 * attempt)
-def _coerce_text(value: Any) -> str:
- if isinstance(value, bytes):
- return value.decode("utf-8", errors="replace")
- return "" if value is None else str(value)
-
-
-def _extract_result_output(result: Any) -> str:
+def _result_parts(result: Any) -> tuple[str, int]:
+ """(output, returncode) from an SDK command result; tolerates raw strings and older result shapes."""
try:
- return _coerce_text(result.output())
+ value = result.output()
except (AttributeError, TypeError):
- return _coerce_text(result)
-
-
-def _extract_result_returncode(result: Any) -> int:
- attr = "exit_code" if hasattr(result, "exit_code") else "returncode"
- exit_code = getattr(result, attr, None)
- return exit_code if isinstance(exit_code, int) else 1
+ value = result
+ if isinstance(value, bytes):
+ value = value.decode("utf-8", errors="replace")
+ exit_code = getattr(result, "exit_code" if hasattr(result, "exit_code") else "returncode", None)
+ return ("" if value is None else str(value)), (exit_code if isinstance(exit_code, int) else 1)
def _load_snapshots() -> dict:
return _load_json_store(get_hermes_home() / _SNAPSHOT_STORE_NAME)
-def _save_snapshots(data: dict) -> None:
- _save_json_store(get_hermes_home() / _SNAPSHOT_STORE_NAME, data)
-
-
-def _get_snapshot_id(task_id: str) -> str | None:
- snapshot_id = _load_snapshots().get(task_id) if task_id else None
- return snapshot_id if isinstance(snapshot_id, str) and snapshot_id else None
-
-
def _store_snapshot(task_id: str, snapshot_id: str) -> None:
if task_id and snapshot_id:
- _save_snapshots({**_load_snapshots(), task_id: snapshot_id})
+ _save_json_store(get_hermes_home() / _SNAPSHOT_STORE_NAME, {**_load_snapshots(), task_id: snapshot_id})
-def _delete_snapshot(task_id: str, snapshot_id: str | None = None) -> None:
+def _delete_snapshot(task_id: str, snapshot_id: str) -> None:
+ """Drop the stored id for ``task_id`` only if it still equals ``snapshot_id``."""
snapshots = _load_snapshots()
- existing = snapshots.get(task_id) if task_id else None
- if existing is not None and (snapshot_id is None or existing == snapshot_id):
- snapshots.pop(task_id, None)
- _save_snapshots(snapshots)
+ if task_id and snapshots.get(task_id) == snapshot_id:
+ snapshots.pop(task_id)
+ _save_json_store(get_hermes_home() / _SNAPSHOT_STORE_NAME, snapshots)
def _extract_snapshot_id(snapshot: Any) -> str | None:
"""Accept SDK objects or raw dicts; attribute lookup first, then dict keys."""
getters = [lambda k: getattr(snapshot, k, None)] + ([snapshot.get] if isinstance(snapshot, dict) else [])
- for get in getters:
- for key in ("snapshot_id", "snapshotId", "id"):
- value = get(key)
- if isinstance(value, str) and value:
- return value
- return None
+ candidates = (get(key) for get in getters for key in ("snapshot_id", "snapshotId", "id"))
+ return next((v for v in candidates if isinstance(v, str) and v), None)
@cache
@@ -189,13 +168,12 @@ class VercelSandboxEnvironment(BaseEnvironment):
def _create_sandbox(self) -> Sandbox:
_ensure_vercel_sdk()
from vercel.sandbox import Sandbox
- snapshot_id = _get_snapshot_id(self._task_id) if self._persistent else None
- if snapshot_id:
+ snapshot_id = _load_snapshots().get(self._task_id) if self._persistent and self._task_id else None
+ if isinstance(snapshot_id, str) and snapshot_id:
try:
- return _retry_vercel_call(
- "sandbox restore",
- lambda: Sandbox.create(**self._create_kwargs, source={"type": "snapshot", "snapshot_id": snapshot_id}),
- attempts=_CREATE_RETRY_ATTEMPTS)
+ source = {"type": "snapshot", "snapshot_id": snapshot_id}
+ return _retry_vercel_call("sandbox restore", lambda: Sandbox.create(**self._create_kwargs, source=source),
+ attempts=_CREATE_RETRY_ATTEMPTS)
except Exception as exc:
logger.warning("Vercel: failed to restore snapshot %s for task %s; falling back to a fresh sandbox: %s",
snapshot_id, self._task_id, exc)
@@ -228,18 +206,18 @@ class VercelSandboxEnvironment(BaseEnvironment):
except Exception as exc:
logger.debug("Vercel: home detection failed for task %s: %s", self._task_id, exc)
return self._workspace_root
- home = _extract_result_output(result).strip()
+ home = _result_parts(result)[0].strip()
return home if home.startswith("/") else self._workspace_root
def _wait_for_running(self, timeout: timedelta = _RUNNING_WAIT_TIMEOUT) -> None:
- sandbox = self._require_sandbox()
+ sandbox, running = self._require_sandbox(), _sandbox_status_type().RUNNING
status = sandbox.status
- if status is None or status == _sandbox_status_type().RUNNING:
+ if status is None or status == running:
return
if _is_terminal(status):
raise RuntimeError(f"Sandbox entered terminal state: {status}")
try:
- sandbox.wait_for_status(_sandbox_status_type().RUNNING, timeout=max(timeout, timedelta(seconds=1)),
+ sandbox.wait_for_status(running, timeout=max(timeout, timedelta(seconds=1)),
poll_interval=timedelta(milliseconds=250))
except TimeoutError as exc:
status = sandbox.status
@@ -247,15 +225,14 @@ class VercelSandboxEnvironment(BaseEnvironment):
raise RuntimeError(f"Sandbox entered terminal state: {status}") from exc
raise RuntimeError(f"Sandbox did not reach running state (last status: {status})") from exc
- def _close_sandbox_client(self, sandbox: Sandbox | None) -> None:
- if sandbox is not None:
- with contextlib.suppress(Exception):
- sandbox.client.close()
+ @staticmethod
+ def _close_sandbox_client(sandbox: Sandbox | None) -> None:
+ with contextlib.suppress(Exception): # None sandbox -> AttributeError -> no-op
+ sandbox.client.close()
- def _stop_sandbox(self, sandbox: Sandbox | None) -> None:
- if sandbox is None:
- return
- with contextlib.suppress(Exception):
+ @staticmethod
+ def _stop_sandbox(sandbox: Sandbox | None) -> None:
+ with contextlib.suppress(Exception): # None sandbox -> AttributeError -> no-op
try:
sandbox.stop(blocking=True, timeout=timedelta(seconds=15), poll_interval=timedelta(milliseconds=500))
except TypeError: # older SDKs: stop() takes no arguments
@@ -295,9 +272,10 @@ class VercelSandboxEnvironment(BaseEnvironment):
self._attach_fresh_sandbox(requested_cwd)
def _run_checked(self, script: str, label: str) -> None:
- result = self._require_sandbox().run_command("bash", ["-lc", script], cwd=self._workspace_root)
- if _extract_result_returncode(result) != 0:
- raise RuntimeError(f"Vercel {label} failed: {_extract_result_output(result).strip()}")
+ output, returncode = _result_parts(
+ self._require_sandbox().run_command("bash", ["-lc", script], cwd=self._workspace_root))
+ if returncode != 0:
+ raise RuntimeError(f"Vercel {label} failed: {output.strip()}")
def _vercel_upload(self, host_path: str, remote_path: str) -> None:
self._vercel_bulk_upload([(host_path, remote_path)])
@@ -332,10 +310,8 @@ class VercelSandboxEnvironment(BaseEnvironment):
self._sync_manager.sync()
def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120, stdin_data: str | None = None):
- """``timeout`` is not forwarded (the SDK has no per-exec timeout); the base
- ``_wait_for_process`` enforces it by killing the sandbox via ``cancel_fn``.
- ``stdin_data`` is discarded: ``_stdin_mode = "heredoc"`` makes the base
- ``execute()`` embed stdin into the command string before calling this."""
+ """``timeout`` is enforced by the base ``_wait_for_process`` via ``cancel_fn`` (the SDK has no
+ per-exec timeout); ``stdin_data`` is already embedded as a heredoc by the base ``execute()``."""
del timeout, stdin_data
sandbox = self._require_sandbox()
workspace_root = self._workspace_root
@@ -346,8 +322,7 @@ class VercelSandboxEnvironment(BaseEnvironment):
self._stop_sandbox(sandbox)
def exec_fn() -> tuple[str, int]:
- result = sandbox.run_command("bash", ["-lc" if login else "-c", cmd_string], cwd=workspace_root)
- return _extract_result_output(result), _extract_result_returncode(result)
+ return _result_parts(sandbox.run_command("bash", ["-lc" if login else "-c", cmd_string], cwd=workspace_root))
return _ThreadedProcessHandle(exec_fn, cancel_fn=cancel)
def cleanup(self):