The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): inline single-use locals and dispatch cwd resolution in remote env backends
Teknium4ba674755846
diff --git a/tools/environments/daytona.py b/tools/environments/daytona.pyindex 5b3edeb019a..15c56959a84 100644--- a/tools/environments/daytona.py+++ b/tools/environments/daytona.py@@ -36,39 +36,33 @@ class DaytonaEnvironment(BaseEnvironment):ensure_lazy_dep("terminal.daytona")from daytona import Daytona, CreateSandboxFromImageParams, DaytonaError, Resources, SandboxState- self._persistent = persistent_filesystem- self._task_id = task_id- self._SandboxState = SandboxState+ self._persistent, self._task_id, self._SandboxState = persistent_filesystem, task_id, SandboxStateself._daytona = Daytona()self._sandbox = Noneself._lock = threading.Lock()- memory_gib = max(1, math.ceil(memory / 1024))- disk_gib = max(1, math.ceil(disk / 1024))+ memory_gib, disk_gib = max(1, math.ceil(memory / 1024)), max(1, math.ceil(disk / 1024))if disk_gib > 10:logger.warning("Daytona: requested disk (%dGB) exceeds platform limit (10GB). ""Capping to 10GB.", disk_gib)disk_gib = 10resources = Resources(cpu=cpu, memory=memory_gib, disk=disk_gib)- labels = {"hermes_task_id": task_id}- sandbox_name = f"hermes-{task_id}"+ labels, sandbox_name = {"hermes_task_id": task_id}, f"hermes-{task_id}"if self._persistent:try:self._sandbox = self._daytona.get(sandbox_name)self._sandbox.start()logger.info("Daytona: resumed sandbox %s for task %s", self._sandbox.id, task_id)- except DaytonaError:- self._sandbox = Noneexcept Exception as e:- logger.warning("Daytona: failed to resume sandbox for task %s: %s", task_id, e)+ if not isinstance(e, DaytonaError): # DaytonaError == not found: silently fall through+ logger.warning("Daytona: failed to resume sandbox for task %s: %s", task_id, e)self._sandbox = Noneif self._sandbox is None:try:# SDK list() is a cursor-paginated iterator (offset pagination is gone).- legacy = next(iter(self._daytona.list(labels=labels, limit=1)), None)- if legacy is not None:- self._sandbox = legacy+ self._sandbox = next(iter(self._daytona.list(labels=labels, limit=1)), None)+ if self._sandbox is not None:self._sandbox.start()logger.info("Daytona: resumed legacy sandbox %s for task %s", self._sandbox.id, task_id)except Exception as e:@@ -96,7 +90,6 @@ class DaytonaEnvironment(BaseEnvironment):self.init_session()def _daytona_upload(self, host_path: str, remote_path: str) -> None:- """Upload a single file via Daytona SDK."""self._sandbox.process.exec(quoted_mkdir_command([str(Path(remote_path).parent)]))self._sandbox.fs.upload_file(host_path, remote_path)@@ -123,7 +116,6 @@ class DaytonaEnvironment(BaseEnvironment):self._sandbox.process.exec(f"rm -f {shlex.quote(remote_tar)}")def _daytona_delete(self, remote_paths: list[str]) -> None:- """Batch-delete remote files via SDK exec."""self._sandbox.process.exec(quoted_rm_command(remote_paths))def _ensure_sandbox_ready(self) -> None:@@ -134,16 +126,13 @@ class DaytonaEnvironment(BaseEnvironment):logger.info("Daytona: restarted sandbox %s", self._sandbox.id)def _before_execute(self) -> None:- """Ensure sandbox is ready, then sync files via FileSyncManager."""with self._lock:self._ensure_sandbox_ready()self._sync_manager.sync()def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,stdin_data: str | None = None):- """Return a _ThreadedProcessHandle wrapping a blocking Daytona SDK call."""- sandbox = self._sandbox- lock = self._lock+ sandbox, lock = self._sandbox, self._lockdef cancel():with lock, contextlib.suppress(Exception):diff --git a/tools/environments/managed_modal.py b/tools/environments/managed_modal.pyindex f5b7af5fd77..0fd65dbf531 100644--- a/tools/environments/managed_modal.py+++ b/tools/environments/managed_modal.py@@ -26,14 +26,18 @@ _TERMINAL_EXEC_STATUSES = frozenset({"completed", "failed", "cancelled", "timeou_CLIENT_TIMEOUT_GRACE_SECONDS = 10.0-def _request_timeout_env(name: str, default: float) -> float:+def _coerce_number(value: Any, default: float) -> float:try:- value = float(os.getenv(name, str(default)))- return value if value > 0 else default+ return default if value is None else float(value)except (TypeError, ValueError):return default+def _request_timeout_env(name: str, default: float) -> float:+ value = _coerce_number(os.getenv(name), default)+ return value if value > 0 else default++def _result(output: str, returncode: int = 1) -> dict:return {"output": output, "returncode": returncode}@@ -66,15 +70,11 @@ class ManagedModalEnvironment(BaseEnvironment):raise ValueError("Managed Modal requires a configured tool gateway and Nous user token")self._gateway_origin = gateway.gateway_origin.rstrip("/")self._nous_user_token = gateway.nous_user_token- self._task_id = task_id- self._persistent = persistent_filesystem- self._image = image+ self._task_id, self._persistent, self._image = task_id, persistent_filesystem, imageself._sandbox_kwargs = dict(modal_sandbox_kwargs or {})self._create_idempotency_key = str(uuid.uuid4())self._sandbox_id = self._create_sandbox()- # -- Execution -------------------------------------------------------def execute(self, command: str, cwd: str = "", *, timeout: int | None = None, stdin_data: str | None = None,rewrite_compound_background: bool = True, bounded_capture: bool = False) -> dict:# Signature parity with BaseEnvironment.execute only: the gateway runs commands@@ -87,12 +87,22 @@ class ManagedModalEnvironment(BaseEnvironment):# Feed sudo via a shell pipe: the transport has no direct stdin piping.exec_command = f"printf '%s\\n' {shlex.quote(sudo_stdin.rstrip())} | {exec_command}"timeout = timeout or self.timeout+ exec_id = str(uuid.uuid4())+ payload: Dict[str, Any] = {"execId": exec_id, "command": exec_command, "cwd": cwd or self.cwd,+ "timeoutMs": int(timeout * 1000)}+ if stdin_data is not None:+ payload["stdinData"] = stdin_datatry:- exec_id, immediate = self._start_exec(exec_command, cwd or self.cwd, timeout, stdin_data)+ response = self._request("POST", f"/v1/sandboxes/{self._sandbox_id}/execs", json=payload, timeout=10)+ body = response.json() if response.status_code < 400 else Noneexcept Exception as exc:return _result(f"Managed Modal exec failed: {exc}")- if immediate is not None:- return immediate+ if body is None:+ return _result(self._format_error("Managed Modal exec failed", response))+ if (final := self._result_from_body(body)) is not None:+ return final+ if body.get("execId") != exec_id:+ return _result("Managed Modal exec start did not return the expected exec id")deadline = time.monotonic() + timeout + _CLIENT_TIMEOUT_GRACE_SECONDS_now = time.monotonic()_activity_state = {"last_touch": _now, "start": _now}@@ -101,11 +111,10 @@ class ManagedModalEnvironment(BaseEnvironment):self._cancel_exec(exec_id)return _result("[Command interrupted - Modal sandbox exec cancelled]", 130)try:- result = self._poll_exec(exec_id)+ if (result := self._poll_exec(exec_id)) is not None:+ return resultexcept Exception as exc:return _result(f"Managed Modal exec failed: {exc}")- if result is not None:- return resultif time.monotonic() >= deadline:self._cancel_exec(exec_id)return _result(f"Managed Modal exec timed out after {timeout}s", 124)@@ -118,46 +127,23 @@ class ManagedModalEnvironment(BaseEnvironment):passtime.sleep(0.25)- def _result_from_body(self, body: dict) -> dict | None:+ @staticmethod+ def _result_from_body(body: dict) -> dict | None:"""Final result dict if the exec body reports a terminal status, else ``None``."""if body.get("status") in _TERMINAL_EXEC_STATUSES:return _result(body.get("output", ""), body.get("returncode", 1))- return None-- def _start_exec(self, command: str, cwd: str, timeout: int,- stdin_data: str | None) -> tuple[str, dict | None]:- """POST the exec; return (exec_id, immediate_result). A non-None result ends execute()."""- exec_id = str(uuid.uuid4())- payload: Dict[str, Any] = {"execId": exec_id, "command": command, "cwd": cwd,- "timeoutMs": int(timeout * 1000)}- if stdin_data is not None:- payload["stdinData"] = stdin_data- try:- response = self._request("POST", f"/v1/sandboxes/{self._sandbox_id}/execs", json=payload, timeout=10)- except Exception as exc:- return exec_id, _result(f"Managed Modal exec failed: {exc}")- if response.status_code >= 400:- 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, _result("Managed Modal exec start did not return the expected exec id")- return exec_id, Nonedef _poll_exec(self, exec_id: str) -> dict | None:try:- status_response = self._request(- "GET", f"/v1/sandboxes/{self._sandbox_id}/execs/{exec_id}",- timeout=(self._CONNECT_TIMEOUT_SECONDS, self._POLL_READ_TIMEOUT_SECONDS))+ response = self._request("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 _result(f"Managed Modal exec poll failed: {exc}")- if status_response.status_code == 404:+ if response.status_code == 404:return _result("Managed Modal exec not found")- if status_response.status_code >= 400:- return _result(self._format_error("Managed Modal exec poll failed", status_response))- return self._result_from_body(status_response.json())+ if response.status_code >= 400:+ return _result(self._format_error("Managed Modal exec poll failed", response))+ return self._result_from_body(response.json())def _cancel_exec(self, exec_id: str) -> None:try:@@ -177,13 +163,11 @@ class ManagedModalEnvironment(BaseEnvironment):finally:self._sandbox_id = None- # -- Gateway HTTP ----------------------------------------------------def _create_sandbox(self) -> str:kw = self._sandbox_kwargs- cpu = self._coerce_number(kw.get("cpu"), 1)- memory = self._coerce_number(kw.get("memoryMiB", kw.get("memory")), 5120)- disk = self._coerce_number(kw.get("ephemeral_disk", kw.get("diskMiB")), None)+ cpu = _coerce_number(kw.get("cpu"), 1)+ memory = _coerce_number(kw.get("memoryMiB", kw.get("memory")), 5120)+ disk = _coerce_number(kw.get("ephemeral_disk", kw.get("diskMiB")), None)create_payload = {"image": self._image, "cwd": self.cwd, "cpu": cpu, "memoryMiB": memory, "timeoutMs": 3_600_000,"idleTimeoutMs": max(300_000, int(self.timeout * 1000)),@@ -206,13 +190,6 @@ class ManagedModalEnvironment(BaseEnvironment):**(extra_headers or {})}return requests.request(method, f"{self._gateway_origin}{path}", headers=headers, json=json, timeout=timeout)- @staticmethod- def _coerce_number(value: Any, default: float) -> float:- try:- return default if value is None else float(value)- except (TypeError, ValueError):- return default-@staticmethoddef _format_error(prefix: str, response: requests.Response) -> str:try:diff --git a/tools/environments/modal.py b/tools/environments/modal.pyindex 85d63d0402f..e90b586935b 100644--- a/tools/environments/modal.py+++ b/tools/environments/modal.py@@ -51,10 +51,10 @@ def _store_direct_snapshot(task_id: str, snapshot_id: str) -> None:def _delete_direct_snapshot(task_id: str, snapshot_id: str | None = None) -> None:snapshots = _load_snapshots()stale = [k for k in (f"direct:{task_id}", task_id)- if snapshots.get(k) is not None and (snapshot_id is None or snapshots[k] == snapshot_id)]+ if snapshots.get(k) is not None and snapshot_id in (None, snapshots[k])]+ for key in stale:+ snapshots.pop(key)if stale:- for key in stale:- snapshots.pop(key, None)_save_snapshots(snapshots)@@ -137,13 +137,10 @@ class ModalEnvironment(BaseEnvironment):modal_sandbox_kwargs: Optional[dict[str, Any]] = None,persistent_filesystem: bool = True, task_id: str = "default"):super().__init__(cwd=cwd, timeout=timeout)- self._persistent = persistent_filesystem- self._task_id = task_id- self._sandbox = None- self._app = None+ self._persistent, self._task_id = persistent_filesystem, task_id+ self._sandbox = self._app = Noneself._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 = (_get_snapshot_restore_candidate(self._task_id) if self._persistent else (None, False))if restored_snapshot_id:@@ -156,32 +153,33 @@ class ModalEnvironment(BaseEnvironment):# from_iterable keeps each source lazy so a failure mid-way leaves the earlier mounts in placefor entry in itertools.chain.from_iterable(fn() for fn in (get_credential_file_mounts, iter_skills_files, iter_cache_files)):- cred_mounts.append(_modal.Mount.from_local_file(entry["host_path"], remote_path=entry["container_path"]))+ cred_mounts.append(+ _modal.Mount.from_local_file(entry["host_path"], remote_path=entry["container_path"]))except Exception as e:logger.debug("Modal: could not load credential file mounts: %s", e)self._worker.start()- async def _create_sandbox(image_spec: Any):- app = await _modal.App.lookup.aio("hermes-agent", create_if_missing=True)- create_kwargs = dict(sandbox_kwargs)- if cred_mounts:- create_kwargs["mounts"] = list(create_kwargs.pop("mounts", [])) + cred_mounts- sandbox = await _modal.Sandbox.create.aio(- "sleep", "infinity", image=image_spec, app=app,- timeout=int(create_kwargs.pop("timeout", 3600)), **create_kwargs)- return app, sandbox+ def _create(image_spec: Any) -> None:+ async def _create_sandbox():+ app = await _modal.App.lookup.aio("hermes-agent", create_if_missing=True)+ create_kwargs = dict(modal_sandbox_kwargs or {})+ if cred_mounts:+ create_kwargs["mounts"] = list(create_kwargs.pop("mounts", [])) + cred_mounts+ sandbox = await _modal.Sandbox.create.aio(+ "sleep", "infinity", image=image_spec, app=app,+ timeout=int(create_kwargs.pop("timeout", 3600)), **create_kwargs)+ return app, sandbox+ self._app, self._sandbox = self._worker.run_coroutine(_create_sandbox(), timeout=300)try:try:- effective_image = _resolve_modal_image(restored_snapshot_id or image)- self._app, self._sandbox = self._worker.run_coroutine(_create_sandbox(effective_image), timeout=300)+ _create(_resolve_modal_image(restored_snapshot_id or image))except Exception as exc:if not restored_snapshot_id:raiselogger.warning("Modal: failed to restore snapshot %s, retrying with base image: %s",restored_snapshot_id[:20], exc)_delete_direct_snapshot(self._task_id, restored_snapshot_id)- self._app, self._sandbox = self._worker.run_coroutine(- _create_sandbox(_resolve_modal_image(image)), timeout=300)+ _create(_resolve_modal_image(image))else:if restored_snapshot_id and restored_from_legacy_key:_store_direct_snapshot(self._task_id, restored_snapshot_id)@@ -196,22 +194,26 @@ class ModalEnvironment(BaseEnvironment):self._sync_manager.sync(force=True)self.init_session()- def _exec_with_stdin(self, cmd: str, payload: str, *, timeout: int, fail_label: str | None = None) -> None:- """Run ``bash -c cmd`` in the sandbox feeding ``payload`` on stdin; when ``fail_label`` is- given a non-zero exit raises with the remote stderr."""+ def _exec(self, cmd: str, *, timeout: int, stdin: str | None = None, fail_label: str | None = None,+ capture: bool = False):+ """Run ``bash -c cmd`` in the sandbox. ``stdin`` is streamed in chunks; ``capture`` returns+ stdout; ``fail_label`` turns a non-zero exit into RuntimeError (with stderr unless capturing)."""async def _run():proc = await self._sandbox.exec.aio("bash", "-c", cmd)- await _stream_stdin(proc, payload, self._STDIN_CHUNK_SIZE)+ if stdin is not None:+ await _stream_stdin(proc, stdin, self._STDIN_CHUNK_SIZE)+ data = await proc.stdout.read.aio() if capture else Noneexit_code = await proc.wait.aio()if fail_label and exit_code != 0:- stderr_text = await proc.stderr.read.aio()- raise RuntimeError(f"Modal {fail_label} failed (exit {exit_code}): {stderr_text}")- self._worker.run_coroutine(_run(), timeout=timeout)+ detail = "" if capture else f": {await proc.stderr.read.aio()}"+ raise RuntimeError(f"Modal {fail_label} failed (exit {exit_code}){detail}")+ return data+ return self._worker.run_coroutine(_run(), timeout=timeout)def _modal_upload(self, host_path: str, remote_path: str) -> None:"""Upload a single file via base64 piped through stdin."""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)+ self._exec(cmd, stdin=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@@ -224,34 +226,21 @@ class ModalEnvironment(BaseEnvironment):tar.add(host_path, arcname=remote_path.lstrip("/"))payload = base64.b64encode(buf.getvalue()).decode("ascii")cmd = f"{quoted_mkdir_command(unique_parent_dirs(files))} && base64 -d | tar xzf - -C /"- self._exec_with_stdin(cmd, payload, timeout=120, fail_label="bulk upload")+ self._exec(cmd, stdin=payload, timeout=120, fail_label="bulk upload")def _modal_bulk_download(self, dest: Path) -> None:"""Download remote .hermes/ as a tar archive (sandboxes run as root, so /root/.hermes)."""- async def _download():- proc = await self._sandbox.exec.aio("bash", "-c", "tar cf - -C / root/.hermes")- data = await proc.stdout.read.aio()- exit_code = await proc.wait.aio()- if exit_code != 0:- raise RuntimeError(f"Modal bulk download failed (exit {exit_code})")- return data.encode() if isinstance(data, str) else data- dest.write_bytes(self._worker.run_coroutine(_download(), timeout=120))+ data = self._exec("tar cf - -C / root/.hermes", timeout=120, fail_label="bulk download", capture=True)+ dest.write_bytes(data.encode() if isinstance(data, str) else data)def _modal_delete(self, remote_paths: list[str]) -> None:- """Batch-delete remote files via exec."""- async def _rm():- proc = await self._sandbox.exec.aio("bash", "-c", quoted_rm_command(remote_paths))- await proc.wait.aio()- self._worker.run_coroutine(_rm(), timeout=15)+ self._exec(quoted_rm_command(remote_paths), timeout=15)def _before_execute(self) -> None:- """Sync files to sandbox via FileSyncManager (rate-limited internally)."""- self._sync_manager.sync()+ self._sync_manager.sync() # rate-limited internallydef _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120, stdin_data: str | None = None):- """Return a _ThreadedProcessHandle wrapping an async Modal sandbox exec."""- sandbox = self._sandbox- worker = self._worker+ sandbox, worker = self._sandbox, self._workerdef cancel():worker.run_coroutine(sandbox.terminate.aio(), timeout=15)@@ -292,5 +281,4 @@ class ModalEnvironment(BaseEnvironment):passfinally:self._worker.stop()- self._sandbox = None- self._app = None+ self._sandbox = self._app = Nonediff --git a/tools/environments/ssh.py b/tools/environments/ssh.pyindex d6a1241b9b3..af654ddc20a 100644--- a/tools/environments/ssh.py+++ b/tools/environments/ssh.py@@ -46,11 +46,7 @@ class SSHEnvironment(BaseEnvironment):def __init__(self, host: str, user: str, cwd: str = "~",timeout: int = 60, port: int = 22, key_path: str = ""):super().__init__(cwd=cwd, timeout=timeout)- self.host = host- self.user = user- self.port = port- self.key_path = key_path-+ self.host, self.user, self.port, self.key_path = host, user, port, key_pathself.control_dir = Path(tempfile.gettempdir()) / "hermes-ssh"self.control_dir.mkdir(parents=True, exist_ok=True)# Short, deterministic socket name: the path must stay under macOS's 104-byte sun_path@@ -114,10 +110,9 @@ class SSHEnvironment(BaseEnvironment):"""Detect the remote user's home directory."""with contextlib.suppress(Exception):result = self._run_ssh("echo $HOME", timeout=10)- home = result.stdout.strip()- if home and result.returncode == 0:- logger.debug("SSH: remote home = %s", home)- return home+ if result.returncode == 0 and result.stdout.strip():+ logger.debug("SSH: remote home = %s", result.stdout.strip())+ return result.stdout.strip()return "/root" if self.user == "root" else f"/home/{self.user}"def _ensure_remote_dirs(self) -> None:@@ -190,7 +185,7 @@ class SSHEnvironment(BaseEnvironment):for proc in (tar_proc, ssh_proc):proc.kill()for proc in (tar_proc, ssh_proc):- proc.wait()+ proc.wait() # kill both first, then reap: never wait on one while the other blocksraise EnvironmentConnectionError("SSH bulk upload timed out",retry_hint=f"Bulk file sync to {self.host} timed out — check the connection and retry.")@@ -216,17 +211,14 @@ class SSHEnvironment(BaseEnvironment):f"File sync from {self.host}")def _ssh_delete(self, remote_paths: list[str]) -> None:- """Batch-delete remote files in one SSH call."""self._run_ssh_checked(quoted_rm_command(remote_paths), 10, "remote rm failed",f"Remote file cleanup on {self.host}")def _before_execute(self) -> None:- """Sync files to remote via FileSyncManager (rate-limited internally)."""- self._sync_manager.sync()+ self._sync_manager.sync() # rate-limited internallydef _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."""return _popen_bash(self._build_ssh_command() + bash_argv(shlex.quote(cmd_string), login), stdin_data)def cleanup(self):diff --git a/tools/environments/vercel_sandbox.py b/tools/environments/vercel_sandbox.pyindex e0a2ebc8cc0..f08eea3f0ce 100644--- a/tools/environments/vercel_sandbox.py+++ b/tools/environments/vercel_sandbox.py@@ -36,7 +36,6 @@ _DEFAULT_CONTAINER_DISK_MB = 51200_CREATE_RETRY_ATTEMPTS = 3_TRANSIENT_STATUS_CODES = frozenset({408, 425, 429, 500, 502, 503, 504})_RUNNING_WAIT_TIMEOUT = timedelta(seconds=30)-_SNAPSHOT_STORE_NAME = "vercel_sandbox_snapshots.json"def _ensure_vercel_sdk() -> None:@@ -87,13 +86,17 @@ def _result_parts(result: Any) -> tuple[str, int]:return ("" if value is None else str(value)), (exit_code if isinstance(exit_code, int) else 1)+def _snapshot_store() -> Path:+ return get_hermes_home() / "vercel_sandbox_snapshots.json"++def _load_snapshots() -> dict:- return _load_json_store(get_hermes_home() / _SNAPSHOT_STORE_NAME)+ return _load_json_store(_snapshot_store())def _store_snapshot(task_id: str, snapshot_id: str) -> None:if task_id and snapshot_id:- _save_json_store(get_hermes_home() / _SNAPSHOT_STORE_NAME, {**_load_snapshots(), task_id: snapshot_id})+ _save_json_store(_snapshot_store(), {**_load_snapshots(), task_id: snapshot_id})def _delete_snapshot(task_id: str, snapshot_id: str) -> None:@@ -101,7 +104,7 @@ def _delete_snapshot(task_id: str, snapshot_id: str) -> None:snapshots = _load_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)+ _save_json_store(_snapshot_store(), snapshots)def _extract_snapshot_id(snapshot: Any) -> str | None:@@ -136,22 +139,18 @@ class VercelSandboxEnvironment(BaseEnvironment):raise ValueError("Vercel Sandbox does not support configurable container_disk. ""Use the default shared setting.")- self._persistent = persistent_filesystem- self._task_id = task_id- self._requested_cwd = cwd+ self._persistent, self._task_id, self._requested_cwd = persistent_filesystem, task_id, cwdself._lock = threading.Lock()self._sandbox: Sandbox | None = None- self._workspace_root = DEFAULT_VERCEL_CWD- self._remote_home = DEFAULT_VERCEL_CWD+ self._workspace_root = self._remote_home = DEFAULT_VERCEL_CWDself._sync_manager: FileSyncManager | None = None_ensure_vercel_sdk()from vercel.sandbox import Resources- vcpus = math.floor(cpu) if cpu > 0 else None- memory_mb = memory if memory > 0 else None- resources = Resources(vcpus=vcpus, memory=memory_mb) if vcpus is not None or memory_mb is not None else None+ vcpus, memory_mb = (math.floor(cpu) if cpu > 0 else None), (memory if memory > 0 else None)self._create_kwargs = {"timeout": max(timedelta(seconds=max(self.timeout, 0)), timedelta(minutes=5)),- "runtime": runtime or None, "resources": resources}+ "runtime": runtime or None,+ "resources": Resources(vcpus=vcpus, memory=memory_mb) if (vcpus, memory_mb) != (None, None) else None}self._attach_fresh_sandbox(cwd)self._sync_manager.sync(force=True)self.init_session()@@ -162,8 +161,7 @@ class VercelSandboxEnvironment(BaseEnvironment):return self._sandboxdef _remote_hermes_dir(self) -> str:- home = self._remote_home- return "/.hermes" if home == "/" else f"{home.rstrip('/')}/.hermes"+ return f"{self._remote_home.rstrip('/')}/.hermes"def _create_sandbox(self) -> Sandbox:_ensure_vercel_sdk()@@ -172,8 +170,9 @@ class VercelSandboxEnvironment(BaseEnvironment):if isinstance(snapshot_id, str) and snapshot_id:try: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)+ 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)@@ -191,14 +190,11 @@ class VercelSandboxEnvironment(BaseEnvironment):container_base = self._remote_hermes_dir()self._sync_manager = FileSyncManager(get_files_fn=lambda: iter_sync_files(container_base),- upload_fn=self._vercel_upload, delete_fn=self._vercel_delete,+ upload_fn=lambda host_path, remote_path: self._vercel_bulk_upload([(host_path, remote_path)]),+ delete_fn=self._vercel_delete,bulk_upload_fn=self._vercel_bulk_upload, bulk_download_fn=self._vercel_bulk_download)- if requested_cwd == "~":- self.cwd = self._remote_home- elif requested_cwd in {"", DEFAULT_VERCEL_CWD}:- self.cwd = self._workspace_root- else:- self.cwd = requested_cwd+ self.cwd = {"~": self._remote_home, "": self._workspace_root,+ DEFAULT_VERCEL_CWD: self._workspace_root}.get(requested_cwd, requested_cwd)def _detect_remote_home(self) -> str:try:@@ -238,20 +234,19 @@ class VercelSandboxEnvironment(BaseEnvironment):except TypeError: # older SDKs: stop() takes no argumentssandbox.stop()- def _snapshot_sandbox(self, sandbox: Sandbox) -> str | None:+ def _snapshot_sandbox(self, sandbox: Sandbox) -> None:if not self._persistent or not self._task_id:- return None+ returntry:snapshot_id = _extract_snapshot_id(sandbox.snapshot())except Exception as exc:logger.warning("Vercel: filesystem snapshot failed for task %s: %s", self._task_id, exc)- return None+ returnif not snapshot_id:logger.warning("Vercel: filesystem snapshot for task %s did not return a snapshot id", self._task_id)- return None+ return_store_snapshot(self._task_id, snapshot_id)logger.info("Vercel: saved filesystem snapshot %s for task %s", snapshot_id, self._task_id)- return snapshot_iddef _ensure_sandbox_ready(self) -> None:"""Reuse a healthy sandbox; recreate when refresh fails or it hit a terminal state."""@@ -277,9 +272,6 @@ class VercelSandboxEnvironment(BaseEnvironment):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)])-def _vercel_bulk_upload(self, files: list[tuple[str, str]]) -> None:if not files:return@@ -313,16 +305,15 @@ class VercelSandboxEnvironment(BaseEnvironment):"""``timeout`` is enforced by the base ``_wait_for_process`` via ``cancel_fn`` (the SDK has noper-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- lock = self._lock+ sandbox, workspace_root, lock = self._require_sandbox(), self._workspace_root, self._lockdef cancel() -> None:with lock:self._stop_sandbox(sandbox)def exec_fn() -> tuple[str, int]:- return _result_parts(sandbox.run_command("bash", ["-lc" if login else "-c", cmd_string], cwd=workspace_root))+ 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):