"""A long-lived process INSIDE a terminal backend with both stdio pipes open. ``BaseEnvironment.execute`` is request/response: it captures output and returns. The desktop that follows the terminal backend needs three things that are not: the RFB byte stream between the Desktop pane and the sandbox's Xvnc, cua-driver's MCP-over-stdio server, and the bot's Chromium, which must outlive the call that started it. All three are "spawn argv in the sandbox, keep stdin/stdout as pipes". Each spawn-per-call backend has a local argv prefix that gives exactly that (``docker exec -i``, ``ssh``); this module is the one place that knows them. SDK backends (modal, daytona, vercel) have no argv prefix: ``exec_prefix`` returns None there and the desktop stays on the gateway host (or refuses, per ``bot_desktop.placement``). Plugin backends that declare ``supports_streams`` supply the prefix from their environment's own ``exec_prefix()``. """ from __future__ import annotations import logging import shlex import socket import subprocess import threading from typing import Optional, Sequence from tools.environments.base import BaseEnvironment logger = logging.getLogger(__name__) def exec_prefix(env: BaseEnvironment, *, user: Optional[str] = None, interactive: bool = True) -> Optional[list[str]]: """Local argv that runs its remainder inside ``env``, or None for backends without one. ``user`` selects the sandbox-side account (docker only; ssh runs as the configured login). ``interactive`` keeps stdin open (``docker exec -i``); ssh always does. """ from tools.environments.docker import DockerEnvironment from tools.environments.ssh import SSHEnvironment if isinstance(env, DockerEnvironment): container = getattr(env, "_container_id", None) if not container: return None argv = [env._docker_exe, "exec"] if interactive: argv.append("-i") if user: argv += ["-u", user] return argv + [container] if isinstance(env, SSHEnvironment): return env._build_ssh_command() return _plugin_exec_prefix(env, user=user, interactive=interactive) def _plugin_exec_prefix(env: BaseEnvironment, *, user: Optional[str], interactive: bool) -> Optional[list[str]]: """A plugin environment's own ``exec_prefix()`` (``TerminalEnvironmentProvider.supports_streams``).""" hook = getattr(env, "exec_prefix", None) if not callable(hook): return None try: prefix = hook(user=user, interactive=interactive) except Exception: logger.warning("%s.exec_prefix() failed; treating the backend as unable to stream", type(env).__name__, exc_info=True) return None if not prefix: return None if not isinstance(prefix, (list, tuple)): # A plain string would be split into one-character argv words. logger.warning("%s.exec_prefix() returned %s, not a list of argv words; treating the backend as unable " "to stream", type(env).__name__, type(prefix).__name__) return None return [str(part) for part in prefix] def sandbox_temp_dir(env: BaseEnvironment) -> str: """``env.get_temp_dir()``, or ``/tmp`` for a plugin environment that doesn't subclass ``BaseEnvironment``.""" get_temp_dir = getattr(env, "get_temp_dir", None) return str(get_temp_dir()) if callable(get_temp_dir) else "/tmp" # no-tmp: ok — sandbox-side temp dir def supports_streams(env: BaseEnvironment) -> bool: return exec_prefix(env, interactive=True) is not None def remote_argv(prefix: Sequence[str], argv: Sequence[str], *, env: Optional[dict] = None, shell_joined: bool = False) -> list[str]: """``prefix`` + a ``bash -c`` that exports ``env`` and execs ``argv``. The script is built once, then delivered the way the client needs it: argv-preserving clients (docker, apptainer) get ``["bash", "-c", script]``; ``shell_joined`` clients (OpenSSH joins the words after the host with spaces and the remote login shell splits them again) get the whole ``bash -c '