Skip to content

tmux

tmux

TmuxControl — async wrapper over the tmux binary.

All interactive sessions live on an isolated tmux server (socket name marianne) so Marianne never touches the user's default tmux server. Sessions are created detached with a fixed virtual terminal size; the agent command is passed as an explicit argv tail (never a joined shell string) so the pane process is the agent itself — pid == pgid == session leader, which is what the baton's PID registration and group-kill plumbing expect.

Every tmux invocation runs with a short per-command timeout: a wedged tmux server must surface as a structured :class:TmuxError (which the driver treats as session-lost), never as a driver hang the sheet timeout cannot reach.

kill_server exists for tests only. Production teardown is always per-session (kill_session) — a server kill would take down every concurrent interactive sheet.

Classes

PaneExit dataclass

PaneExit(status, signal)

How a pane's process ended: an exit status, or the signal that killed it.

TmuxError

TmuxError(message, *, stderr='', timed_out=False)

Bases: RuntimeError

A tmux control command failed or timed out.

The driver treats any TmuxError during DRIVE as session-lost; during LAUNCH it is a startup failure. stderr carries tmux's own message for diagnostics.

Source code in src/marianne/execution/instruments/interactive/tmux.py
def __init__(self, message: str, *, stderr: str = "", timed_out: bool = False) -> None:
    super().__init__(message)
    self.stderr = stderr
    self.timed_out = timed_out

TmuxControl

TmuxControl(socket_name=None)

Async control surface over an isolated tmux server.

One instance per socket name; safe to share across sessions (tmux serializes commands server-side). All methods raise :class:TmuxError on failure or per-command timeout.

Source code in src/marianne/execution/instruments/interactive/tmux.py
def __init__(self, socket_name: str | None = None) -> None:
    if socket_name is None:
        socket_name = os.environ.get(SOCKET_ENV_VAR, _DEFAULT_SOCKET)
    if not socket_name or "/" in socket_name:
        raise ValueError(f"invalid tmux socket name: {socket_name!r}")
    self._socket_name = socket_name
Attributes
socket_name property
socket_name

The tmux server socket name (tmux -L <name>).

Methods:
version async
version()

Parse the tmux version, or None when unparseable.

Returns (major, minor); suffixes like 3.4a parse as (3, 4).

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def version(self) -> tuple[int, int] | None:
    """Parse the tmux version, or None when unparseable.

    Returns (major, minor); suffixes like ``3.4a`` parse as (3, 4).
    """
    try:
        _, stdout, _ = await self._run("-V")
    except TmuxError:
        return None
    match = re.search(r"(\d+)\.(\d+)", stdout)
    if not match:
        return None
    return int(match.group(1)), int(match.group(2))
new_session async
new_session(session, command, *, cwd, width, height, env=None)

Create a detached session running command as the pane process.

The command is passed as an explicit argv tail — tmux execs it directly (no shell), so the pane process is the agent itself in its own process group (spike-verified; integration tests pin this). When supplied, env replaces the server environment via env -i. The wrapper execs the target, preserving the pane PID/process group. None retains tmux inheritance for callers without an environment policy.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def new_session(
    self,
    session: str,
    command: list[str],
    *,
    cwd: Path,
    width: int,
    height: int,
    env: dict[str, str] | None = None,
) -> None:
    """Create a detached session running ``command`` as the pane process.

    The command is passed as an explicit argv tail — tmux execs it
    directly (no shell), so the pane process is the agent itself in its
    own process group (spike-verified; integration tests pin this).
    When supplied, ``env`` replaces the server environment via ``env -i``.
    The wrapper execs the target, preserving the pane PID/process group.
    None retains tmux inheritance for callers without an environment policy.
    """
    if not command:
        raise ValueError("command must be non-empty")
    if env is not None:
        command = ["env", "-i", "--", *(f"{k}={v}" for k, v in env.items()), *command]
    await self._run(
        "new-session",
        "-d",
        "-s", session,
        "-x", str(width),
        "-y", str(height),
        "-c", str(cwd),
        "--",
        *command,
    )
    # Keep the pane after its process exits so the driver can read HOW
    # it died (exit status or signal) instead of finding the session
    # gone and reporting "session died" with no cause (18 such reports
    # in one night). The driver kills the session on every outcome, so
    # a dead pane never outlives its attempt.
    # Window option: the target needs the window suffix (``=name:``);
    # ``=name`` alone is "no such window" on tmux 3.4.
    await self._run(
        "set-option", "-t", f"={session}:", "remain-on-exit", "on",
        allow_failure=True,
    )
has_session async
has_session(session)

Whether the session exists on this server.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def has_session(self, session: str) -> bool:
    """Whether the session exists on this server."""
    code, _, _ = await self._run(
        "has-session", "-t", f"={session}", allow_failure=True,
    )
    return code == 0
kill_session async
kill_session(session)

Kill the session. Idempotent — a missing session is not an error.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def kill_session(self, session: str) -> None:
    """Kill the session. Idempotent — a missing session is not an error."""
    await self._run("kill-session", "-t", f"={session}", allow_failure=True)
list_sessions async
list_sessions(prefix='')

List session names on this server, optionally prefix-filtered.

Returns an empty list when the server is not running.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def list_sessions(self, prefix: str = "") -> list[str]:
    """List session names on this server, optionally prefix-filtered.

    Returns an empty list when the server is not running.
    """
    code, stdout, _ = await self._run(
        "list-sessions", "-F", "#{session_name}", allow_failure=True,
    )
    if code != 0:
        return []
    names = [line.strip() for line in stdout.splitlines() if line.strip()]
    if prefix:
        names = [n for n in names if n.startswith(prefix)]
    return names
capture_screen async
capture_screen(session)

Capture the session's rendered screen as plain text.

capture-pane -p without -e renders to plain text — no ANSI escape sequences (spike-verified), so the result is directly pattern-matchable.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def capture_screen(self, session: str) -> str:
    """Capture the session's rendered screen as plain text.

    ``capture-pane -p`` without ``-e`` renders to plain text — no ANSI
    escape sequences (spike-verified), so the result is directly
    pattern-matchable.
    """
    _, stdout, _ = await self._run(
        "capture-pane", "-p", "-t", f"={session}:",
    )
    return stdout
pane_exit async
pane_exit(session)

How the pane's process ended, or None while it is still running.

Reads tmux's pane_dead / pane_dead_status / pane_dead_signal (tmux 3.0+). A vanished session or a tmux failure also reads as None — the caller already knows the session is unusable and only wants the cause when tmux still holds the dead pane.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def pane_exit(self, session: str) -> PaneExit | None:
    """How the pane's process ended, or None while it is still running.

    Reads tmux's ``pane_dead`` / ``pane_dead_status`` / ``pane_dead_signal``
    (tmux 3.0+). A vanished session or a tmux failure also reads as None —
    the caller already knows the session is unusable and only wants the
    cause when tmux still holds the dead pane.
    """
    # ``pane_dead`` is set when the pty closes; the status and signal
    # land on the later SIGCHLD reap. Under load a probe can fall in
    # between (seen in parallel test runs), so give the reap a moment
    # before settling for "status unknown".
    status: int | None = None
    signal: int | None = None
    for attempt in range(_PANE_EXIT_SETTLE_POLLS):
        code, stdout, _ = await self._run(
            "display-message", "-p", "-t", f"={session}:",
            "#{pane_dead}\t#{pane_dead_status}\t#{pane_dead_signal}",
            allow_failure=True,
        )
        if code != 0:
            return None
        parts = stdout.rstrip("\n").split("\t")
        if len(parts) != 3 or parts[0].strip() != "1":
            return None
        raw_status, raw_signal = parts[1].strip(), parts[2].strip()
        status = int(raw_status) if raw_status.lstrip("-").isdigit() else None
        signal = int(raw_signal) if raw_signal.isdigit() else None
        if status is not None or signal is not None:
            break
        if attempt + 1 < _PANE_EXIT_SETTLE_POLLS:
            await asyncio.sleep(_PANE_EXIT_SETTLE_SECONDS)
    return PaneExit(status=status, signal=signal)
pane_pid async
pane_pid(session)

The pane process PID, or None when unavailable.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def pane_pid(self, session: str) -> int | None:
    """The pane process PID, or None when unavailable."""
    code, stdout, _ = await self._run(
        "list-panes", "-t", f"={session}:", "-F", "#{pane_pid}",
        allow_failure=True,
    )
    if code != 0:
        return None
    first = stdout.strip().splitlines()
    if not first:
        return None
    try:
        return int(first[0].strip())
    except ValueError:
        return None
send_keys async
send_keys(session, keys)

Send key names (tmux key syntax, e.g. 'Enter', 'Escape').

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def send_keys(self, session: str, keys: list[str]) -> None:
    """Send key names (tmux key syntax, e.g. 'Enter', 'Escape')."""
    if not keys:
        return
    await self._run("send-keys", "-t", f"={session}:", *keys)
paste_text async
paste_text(session, text)

Deliver text to the session via a named buffer paste.

Uses load-buffer from a private temp file + bracketed paste (paste-buffer -p), which delivers arbitrary multiline UTF-8 without key-escaping issues or ARG_MAX limits. The buffer name is per-session so concurrent sheets never clobber each other; -d deletes the buffer after pasting. Does NOT submit — callers send Enter separately.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def paste_text(self, session: str, text: str) -> None:
    """Deliver text to the session via a named buffer paste.

    Uses load-buffer from a private temp file + bracketed paste
    (``paste-buffer -p``), which delivers arbitrary multiline UTF-8
    without key-escaping issues or ARG_MAX limits. The buffer name is
    per-session so concurrent sheets never clobber each other; ``-d``
    deletes the buffer after pasting. Does NOT submit — callers send
    Enter separately.
    """
    buffer_name = f"mzt-{session}"
    fd, tmp_name = tempfile.mkstemp(prefix="mzt-prompt-", suffix=".txt")
    tmp_path = Path(tmp_name)
    try:
        with os.fdopen(fd, "wb") as fh:
            fh.write(text.encode("utf-8"))
        await self._run("load-buffer", "-b", buffer_name, str(tmp_path))
        await self._run(
            "paste-buffer", "-p", "-d", "-b", buffer_name,
            "-t", f"={session}:",
        )
    finally:
        try:
            tmp_path.unlink(missing_ok=True)
        except OSError:
            pass
pipe_pane_to_file async
pipe_pane_to_file(session, log_path)

Stream the pane's raw output to log_path.

The raw stream is a debug artifact (cursor-addressing soup from TUIs) — it is never machine-parsed. State detection uses :meth:capture_screen exclusively.

The file is truncated first (GH #398): transcript names are keyed by job/sheet/attempt, and a later run that reuses that identity must not inherit — and misattribute — a previous run's session content.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def pipe_pane_to_file(self, session: str, log_path: Path) -> None:
    """Stream the pane's raw output to ``log_path``.

    The raw stream is a debug artifact (cursor-addressing soup from
    TUIs) — it is never machine-parsed. State detection uses
    :meth:`capture_screen` exclusively.

    The file is truncated first (GH #398): transcript names are keyed by
    job/sheet/attempt, and a later run that reuses that identity must not
    inherit — and misattribute — a previous run's session content.
    """
    log_path.parent.mkdir(parents=True, exist_ok=True)
    log_path.write_bytes(b"")
    # pipe-pane runs the command via the tmux server's shell; quote the
    # path defensively (it is daemon-constructed, not user input).
    quoted = str(log_path).replace("'", "'\\''")
    await self._run(
        "pipe-pane", "-o", "-t", f"={session}:", f"cat >> '{quoted}'",
    )
pipe_pane_off async
pipe_pane_off(session)

Stop streaming the pane's output (idempotent).

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def pipe_pane_off(self, session: str) -> None:
    """Stop streaming the pane's output (idempotent)."""
    await self._run("pipe-pane", "-t", f"={session}:", allow_failure=True)
kill_server async
kill_server()

Kill the entire tmux server. TESTS ONLY.

Never call from production paths — it destroys every concurrent interactive session on the socket.

Source code in src/marianne/execution/instruments/interactive/tmux.py
async def kill_server(self) -> None:
    """Kill the entire tmux server. TESTS ONLY.

    Never call from production paths — it destroys every concurrent
    interactive session on the socket.
    """
    await self._run("kill-server", allow_failure=True)

Functions:

sanitize_session_name

sanitize_session_name(raw)

Sanitize a string into a valid tmux session name.

Replaces unsafe characters with - and caps the length. Deterministic: the same input always produces the same name (cleanup relies on this).

Source code in src/marianne/execution/instruments/interactive/tmux.py
def sanitize_session_name(raw: str) -> str:
    """Sanitize a string into a valid tmux session name.

    Replaces unsafe characters with ``-`` and caps the length. Deterministic:
    the same input always produces the same name (cleanup relies on this).
    """
    if not raw:
        raise ValueError("session name must be non-empty")
    cleaned = _SESSION_NAME_SAFE.sub("-", raw).strip("-")
    if not cleaned:
        raise ValueError(f"session name {raw!r} sanitizes to empty")
    if len(cleaned) <= _SESSION_NAME_MAX:
        return cleaned
    # Truncation must stay collision-resistant (goal-mode audit, GPT P1):
    # a bare prefix cut maps two long inputs — or two sheets of one
    # long-named job, whose -sN-aM identity falls past the cap — onto ONE
    # session name, and the pre-launch same-name cleanup then kills the
    # OTHER live sheet (and completion markers cross jobs). A digest of
    # the FULL raw input keeps the name bounded, deterministic, and
    # distinct per distinct input.
    digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:10]
    return f"{cleaned[: _SESSION_NAME_MAX - 11]}-{digest}"

job_session_prefix

job_session_prefix(job_id)

Prefix shared by ordinary per-attempt sessions for one job.

Session names are generated as mzt-{job_id}-s{sheet}-a{attempt} after sanitization. The -s suffix keeps job from matching job2 while still matching every sheet/attempt for the job.

Source code in src/marianne/execution/instruments/interactive/tmux.py
def job_session_prefix(job_id: str) -> str:
    """Prefix shared by ordinary per-attempt sessions for one job.

    Session names are generated as ``mzt-{job_id}-s{sheet}-a{attempt}`` after
    sanitization. The ``-s`` suffix keeps ``job`` from matching ``job2`` while
    still matching every sheet/attempt for the job.
    """
    return f"{SESSION_SWEEP_PREFIX}{sanitize_session_name(job_id)}-s"

kill_sessions_with_prefix_sync

kill_sessions_with_prefix_sync(prefix, *, socket_name=None)

Best-effort synchronous tmux sweep for sessions with prefix.

BatonAdapter.deregister_job is deliberately synchronous, but cancelled interactive attempts live outside the daemon process tree in tmux. This helper gives the sync cancellation path a tmux-session teardown backstop. Missing tmux or missing server is a no-op; individual kill failures are logged and do not abort the sweep.

Source code in src/marianne/execution/instruments/interactive/tmux.py
def kill_sessions_with_prefix_sync(
    prefix: str,
    *,
    socket_name: str | None = None,
) -> list[str]:
    """Best-effort synchronous tmux sweep for sessions with ``prefix``.

    ``BatonAdapter.deregister_job`` is deliberately synchronous, but cancelled
    interactive attempts live outside the daemon process tree in tmux. This
    helper gives the sync cancellation path a tmux-session teardown backstop.
    Missing tmux or missing server is a no-op; individual kill failures are
    logged and do not abort the sweep.
    """
    if not prefix:
        raise ValueError("prefix must be non-empty")
    control = TmuxControl(socket_name)
    base_cmd = ["tmux", "-L", control.socket_name]
    try:
        listed = subprocess.run(
            [*base_cmd, "list-sessions", "-F", "#{session_name}"],
            check=False,
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="replace",
            timeout=_SYNC_COMMAND_TIMEOUT_SECONDS,
        )
    except FileNotFoundError:
        return []
    except subprocess.TimeoutExpired:
        _logger.warning(
            "tmux_sync_list_timeout",
            socket=control.socket_name,
            prefix=prefix,
        )
        return []

    if listed.returncode != 0:
        return []

    sessions = [
        line.strip()
        for line in listed.stdout.splitlines()
        if line.strip().startswith(prefix)
    ]
    killed: list[str] = []
    for session in sessions:
        try:
            result = subprocess.run(
                [*base_cmd, "kill-session", "-t", f"={session}"],
                check=False,
                capture_output=True,
                text=True,
                encoding="utf-8",
                errors="replace",
                timeout=_SYNC_COMMAND_TIMEOUT_SECONDS,
            )
        except subprocess.TimeoutExpired:
            _logger.warning(
                "tmux_sync_kill_timeout",
                socket=control.socket_name,
                session=session,
            )
            continue
        except FileNotFoundError:
            return killed
        if result.returncode == 0:
            killed.append(session)
        else:
            _logger.warning(
                "tmux_sync_kill_failed",
                socket=control.socket_name,
                session=session,
                stderr=result.stderr.strip(),
            )
    return killed