Skip to content

Index

interactive

Interactive instrument execution — tmux-driven live agent sessions.

Instead of single-pass headless execution (claude -p), interactive mode launches the agent CLI as a live TUI inside an isolated tmux server, submits the sheet prompt, and a driver state machine pushes the agent to completion.

See docs/specs/2026-06-10-interactive-mode-design.md.

Classes

InteractiveCliBackend

InteractiveCliBackend(profile, working_directory=None, tmux=None)

Bases: WorkspaceMcpConfigMixin, Backend

Backend that drives a CLI instrument through a live tmux session.

One instance per concurrent interactive sheet (pooled in a free-list separate from headless instances). All per-attempt state is local to execute(); the attempt identity set by the adapter is consumed and cleared each execution, so free-list reuse is inherently clean.

Initialize from an InstrumentProfile with interactive config.

Parameters:

Name Type Description Default
profile InstrumentProfile

Instrument profile; must be kind=cli with a cli.interactive block (verified instruments only).

required
working_directory Path | None

Working directory (the sheet workspace).

None
tmux TmuxControl | None

TmuxControl override for tests; defaults to the shared marianne socket.

None

Raises:

Type Description
ValueError

If the profile cannot run interactively.

Source code in src/marianne/execution/instruments/interactive/backend.py
def __init__(
    self,
    profile: InstrumentProfile,
    working_directory: Path | None = None,
    tmux: TmuxControl | None = None,
) -> None:
    """Initialize from an InstrumentProfile with interactive config.

    Args:
        profile: Instrument profile; must be kind=cli with a
            ``cli.interactive`` block (verified instruments only).
        working_directory: Working directory (the sheet workspace).
        tmux: TmuxControl override for tests; defaults to the shared
            ``marianne`` socket.

    Raises:
        ValueError: If the profile cannot run interactively.
    """
    if profile.kind != "cli" or profile.cli is None:
        raise ValueError(
            f"InteractiveCliBackend requires kind=cli, got "
            f"kind={profile.kind} for instrument '{profile.name}'"
        )
    if profile.cli.interactive is None:
        raise ValueError(
            f"Instrument '{profile.name}' has no cli.interactive config — "
            f"interactive mode is only available for instruments whose "
            f"interactive behavior has been verified. Add a "
            f"cli.interactive block to the profile or remove "
            f"'interactive: true' from the score."
        )

    self._profile = profile
    self._cli = profile.cli
    self._interactive: InteractiveCliConfig = profile.cli.interactive
    self._working_directory: Path | None = working_directory
    self._tmux = tmux or TmuxControl()
    self._driver = InteractiveSessionDriver(self._tmux, self._interactive)

    self._mcp_config_path: Path | None = None
    self._model: str | None = profile.default_model
    self._preamble: str | None = None
    self._prompt_extensions: list[str] = []

    # Per-sheet driver knobs — set by the adapter after acquire,
    # re-set on every dispatch (and reset by clear_overrides).
    self._max_nudges: int = DEFAULT_MAX_NUDGES
    self._nudge_message: str | None = None
    self._nudge_policy = "static"
    self._nudge_instrument: str | None = None
    self._nudge_timeout_seconds = 30.0
    self._nudge_backend_factory: BackendFactory | None = None

    # Attempt identity — set by the adapter after acquire; consumed
    # (and cleared) by the next execute(). Without it, execute()
    # falls back to a unique token (standalone use).
    self._attempt_identity: tuple[str, int, int] | None = None

    # PID callbacks — same contract as PluginCliBackend; wired by the
    # pool/adapter. The pane process is its own pgid (spike-verified,
    # integration-pinned), so the group callback gets (pid, pid).
    self._on_process_spawned: Callable[[int], None] | None = None
    self._on_process_exited: Callable[[int], None] | None = None
    self._on_process_group_spawned: Callable[[int, int], None] | None = None
    # Live output sink — same contract as PluginCliBackend (#352 inc-3);
    # the adapter wires the OutputStreamHub writer per dispatch (GH #381).
    self._on_output: Callable[[str, bytes], None] | None = None

    # Override tracking — mirrors PluginCliBackend.
    self._saved_model: str | None = None
    self._has_overrides: bool = False

    _logger.debug(
        "interactive_backend_initialized",
        instrument=profile.name,
        executable=self._cli.command.executable,
        model=self._model,
    )
Attributes
name property
name

Human-readable backend name.

Methods:
set_output_callback
set_output_callback(callback)

Set (or clear with None) the live output sink (GH #381).

Receives ("stdout", chunk) for each new slice of the pipe-pane transcript, once per driver poll. Runs on the event loop; keep it cheap. Without a transcript (capture failed) nothing is delivered.

Source code in src/marianne/execution/instruments/interactive/backend.py
def set_output_callback(
    self, callback: Callable[[str, bytes], None] | None
) -> None:
    """Set (or clear with None) the live output sink (GH #381).

    Receives ``("stdout", chunk)`` for each new slice of the pipe-pane
    transcript, once per driver poll. Runs on the event loop; keep it
    cheap. Without a transcript (capture failed) nothing is delivered.
    """
    self._on_output = callback
set_mcp_config
set_mcp_config(config_path)

Connect this attempt to the pool via a flag or workspace config file.

Source code in src/marianne/execution/instruments/interactive/backend.py
def set_mcp_config(self, config_path: Path | None) -> None:
    """Connect this attempt to the pool via a flag or workspace config file."""
    self._mcp_config_path = config_path
set_attempt_identity
set_attempt_identity(job_id, sheet_num, attempt)

Record the attempt identity for session/marker naming.

Called by the baton adapter after acquire, before execute(). Consumed by the next execute() and cleared — never carries across free-list reuse.

Source code in src/marianne/execution/instruments/interactive/backend.py
def set_attempt_identity(
    self, job_id: str, sheet_num: int, attempt: int,
) -> None:
    """Record the attempt identity for session/marker naming.

    Called by the baton adapter after acquire, before execute().
    Consumed by the next execute() and cleared — never carries across
    free-list reuse.
    """
    self._attempt_identity = (job_id, sheet_num, attempt)
configure_interactive
configure_interactive(*, max_nudges=None, nudge_message=None, nudge_policy=None, nudge_instrument=None, nudge_timeout_seconds=None, backend_factory=None)

Apply per-sheet interactive knobs from instrument_config.

Source code in src/marianne/execution/instruments/interactive/backend.py
def configure_interactive(
    self,
    *,
    max_nudges: int | None = None,
    nudge_message: str | None = None,
    nudge_policy: str | None = None,
    nudge_instrument: str | None = None,
    nudge_timeout_seconds: float | None = None,
    backend_factory: BackendFactory | None = None,
) -> None:
    """Apply per-sheet interactive knobs from instrument_config."""
    if nudge_policy is not None and nudge_policy not in {"static", "model"}:
        raise ValueError("nudge_policy must be static or model")
    if nudge_timeout_seconds is not None and (
        not math.isfinite(nudge_timeout_seconds) or nudge_timeout_seconds <= 0
    ):
        raise ValueError("nudge timeout must be finite and > 0")
    if nudge_instrument is not None and not nudge_instrument.strip():
        raise ValueError("nudge instrument must be non-empty")
    if nudge_policy is not None:
        self._nudge_policy = nudge_policy
    if nudge_instrument is not None:
        self._nudge_instrument = nudge_instrument
    if nudge_timeout_seconds is not None:
        self._nudge_timeout_seconds = nudge_timeout_seconds
    if backend_factory is not None:
        self._nudge_backend_factory = backend_factory
    if max_nudges is not None:
        if max_nudges < 0:
            raise ValueError(f"max_nudges must be >= 0, got {max_nudges}")
        self._max_nudges = max_nudges
    if nudge_message is not None:
        self._nudge_message = nudge_message
apply_overrides
apply_overrides(overrides)

Apply per-sheet parameter overrides (model).

Source code in src/marianne/execution/instruments/interactive/backend.py
def apply_overrides(self, overrides: dict[str, object]) -> None:
    """Apply per-sheet parameter overrides (model)."""
    if not overrides:
        return
    self._saved_model = self._model
    self._has_overrides = True
    if "model" in overrides:
        self._model = str(overrides["model"])
clear_overrides
clear_overrides()

Restore defaults after execution (called on pool release).

Source code in src/marianne/execution/instruments/interactive/backend.py
def clear_overrides(self) -> None:
    """Restore defaults after execution (called on pool release)."""
    if self._has_overrides:
        self._model = self._saved_model
        self._saved_model = None
        self._has_overrides = False
    # Per-sheet knobs and identity never survive into the free list.
    self._max_nudges = DEFAULT_MAX_NUDGES
    self._nudge_message = None
    self._nudge_policy = "static"
    self._nudge_instrument = None
    self._nudge_timeout_seconds = 30.0
    self._nudge_backend_factory = None
    self._attempt_identity = None
    self._mcp_config_path = None
    # W-F3: per-sheet prompt bytes neither — see Backend.set_preamble.
    self._preamble = None
    self._prompt_extensions = []
set_preamble
set_preamble(preamble)

Set preamble to prepend to the next prompt.

Direct-use contract: the dispatch path carries the per-attempt preamble request-locally (SheetRequestState) — see Backend.set_preamble.

Source code in src/marianne/execution/instruments/interactive/backend.py
def set_preamble(self, preamble: str | None) -> None:
    """Set preamble to prepend to the next prompt.

    Direct-use contract: the dispatch path carries the per-attempt
    preamble request-locally (``SheetRequestState``) — see
    ``Backend.set_preamble``.
    """
    self._preamble = preamble
set_prompt_extensions
set_prompt_extensions(extensions)

Set prompt extensions to append to the next prompt.

Direct-use contract — see Backend.set_prompt_extensions.

Source code in src/marianne/execution/instruments/interactive/backend.py
def set_prompt_extensions(self, extensions: list[str]) -> None:
    """Set prompt extensions to append to the next prompt.

    Direct-use contract — see ``Backend.set_prompt_extensions``.
    """
    self._prompt_extensions = list(extensions)
effort_refusal
effort_refusal(level, *, schema_mode)

Why this instrument cannot run a sheet at level (None = it can).

Judged as an interactive launch: a mapping whose interactive is false refuses every level here.

Source code in src/marianne/execution/instruments/interactive/backend.py
def effort_refusal(self, level: str, *, schema_mode: bool) -> str | None:
    """Why this instrument cannot run a sheet at ``level`` (None = it can).

    Judged as an interactive launch: a mapping whose ``interactive`` is
    false refuses every level here.
    """
    return self._profile.effort_refusal(
        level, model=self._model, schema_mode=schema_mode, interactive=True,
    )
tools_refusal
tools_refusal(tools)

Why this instrument cannot run a sheet with tools (None = it can).

Judged as an interactive launch (a mapping with interactive: false refuses every list here).

Source code in src/marianne/execution/instruments/interactive/backend.py
def tools_refusal(self, tools: list[str]) -> str | None:
    """Why this instrument cannot run a sheet with ``tools`` (None = it can).

    Judged as an interactive launch (a mapping with ``interactive: false``
    refuses every list here).
    """
    return self._profile.tools_refusal(tools, interactive=True)
execute async
execute(prompt, *, timeout_seconds=None, request=None)

Execute a prompt by driving a live interactive session.

Returns an ExecutionResult mapped from the driver outcome; never raises for session-level failures (the musician's exception path is reserved for genuine bugs).

Source code in src/marianne/execution/instruments/interactive/backend.py
async def execute(
    self,
    prompt: str,
    *,
    timeout_seconds: float | None = None,
    request: SheetRequestState | None = None,
) -> ExecutionResult:
    """Execute a prompt by driving a live interactive session.

    Returns an ExecutionResult mapped from the driver outcome; never
    raises for session-level failures (the musician's exception path is
    reserved for genuine bugs).
    """
    effective_timeout = timeout_seconds or self._profile.default_timeout_seconds
    session, attempt_label, marker = self._resolve_identity()
    workspace = self._working_directory or Path.cwd()
    workspace.mkdir(parents=True, exist_ok=True)
    marker.parent.mkdir(parents=True, exist_ok=True)
    transcript = _TRANSCRIPT_DIR / f"{session}.log"

    # Request-local per-sheet prompt state (W-F3) — see the CLI backend.
    if request is not None:
        req_preamble: str | None = request.preamble
        req_extensions: tuple[str, ...] | None = request.prompt_extensions
    else:
        req_preamble = None
        req_extensions = None

    command = self._build_command(
        effort=request.effort if request is not None else None,
        tools=request.tools if request is not None else None,
    )
    # GH #533: choose the session id so the harness's own usage record
    # can be found after the sheet, when the profile declares one.
    usage_cfg = self._interactive.usage
    usage_session_id: str | None = None
    if usage_cfg is not None:
        usage_session_id = str(uuid.uuid4())
        command = [*command, usage_cfg.session_id_flag, usage_session_id]
    # GH #487: per-attempt supervisor forensic report, next to the raw
    # transcript (same deliberate outside-any-workspace home: a debug
    # artifact whose writes must not freshen workspace mtimes). The
    # driver reads it on session_lost so the detail names the signal the
    # supervisor forwarded and whether it escalated — an absent report
    # is itself evidence (external kill).
    supervisor_report_path = _TRANSCRIPT_DIR / f"{session}.supervisor.json"
    if self._cli.command.supervise:
        # The pane process stays its own group leader (the supervisor is
        # the leader; the agent shares the group), so pid == pgid holds.
        command = supervised_argv(
            command, io_priority=self._cli.command.io_priority,
            max_open_files=self._cli.command.max_open_files,
            report_path=supervisor_report_path,
        )
    full_prompt = self._build_prompt(
        prompt, marker, req_preamble, req_extensions
    )
    policy = self._build_nudge_policy()

    pane_pid: int | None = None

    def _register_pid(pid: int) -> None:
        nonlocal pane_pid
        pane_pid = pid
        if self._on_process_spawned is not None:
            self._on_process_spawned(pid)
        if self._on_process_group_spawned is not None:
            # pane pid == its own pgid (spike-verified, test-pinned)
            self._on_process_group_spawned(pid, pid)

    _logger.info(
        "interactive_execute_start",
        instrument=self._profile.name,
        session=session,
        attempt=attempt_label,
        prompt_length=len(full_prompt),
        timeout=effective_timeout,
    )

    start = time.monotonic()
    target = self._workspace_mcp_config_target()
    workspace_lock: asyncio.Lock | None = None
    lock_acquired = False
    restore: tuple[Path, bytes | None, bool, int | None] | None = None
    try:
        if target is not None:
            workspace_lock = MCP_WORKSPACE_CONFIG_LOCKS.setdefault(
                target.resolve(), asyncio.Lock(),
            )
            await workspace_lock.acquire()
            lock_acquired = True
            restore = self._materialize_workspace_mcp_config(target)
        driver_result = await self._driver.run(
            session=session,
            command=command,
            cwd=workspace,
            prompt=full_prompt,
            marker_path=marker,
            timeout_seconds=effective_timeout,
            policy=policy,
            max_nudges=self._max_nudges,
            transcript_path=transcript,
            supervisor_report_path=(
                supervisor_report_path
                if self._cli.command.supervise else None
            ),
            on_pane_pid=_register_pid,
            env=self._instrument_env(
                workspace, sheet_num=request.sheet_num if request is not None else None,
            ),
            on_output=self._on_output,
        )
    finally:
        try:
            await self._ensure_session_gone(session)
        finally:
            if restore is not None:
                self._restore_workspace_mcp_config(restore)
            if workspace_lock is not None and lock_acquired:
                workspace_lock.release()
        # The pane process should be dead here. This PID is an UNTRACK
        # TOKEN, not a live process reference — the OS may have recycled
        # it. Consumers must only ever remove it from tracking
        # (pgroup.untrack does exactly that); never signal it directly
        # (goal-mode audit, GLM P2-LOW).
        if pane_pid is not None and self._on_process_exited is not None:
            self._on_process_exited(pane_pid)

    duration = time.monotonic() - start
    # The driver may hold a parsed supervisor report (session_lost path);
    # expose it for observability even when the mapped result does not
    # carry it in the error message.
    supervisor_report = driver_result.supervisor_report
    if supervisor_report is not None:
        _logger.info(
            "interactive_supervisor_report",
            instrument=self._profile.name,
            session=session,
            attempt=attempt_label,
            forwarded_signals=supervisor_report.get("forwarded_signals"),
            escalated_to_sigkill=supervisor_report.get("escalated_to_sigkill"),
            escalated_after_seconds=supervisor_report.get(
                "escalated_after_seconds"
            ),
        )
    result = self._map_result(driver_result, duration)
    # GH #533: on EVERY outcome the attempt cost tokens; never a free zero.
    reading = await asyncio.to_thread(
        read_session_usage, usage_cfg, usage_session_id,
    )
    apply_usage(result, reading)
    _logger.info(
        "interactive_usage_read",
        instrument=self._profile.name,
        session=session,
        outcome=driver_result.outcome,
        measured=reading.measured,
        responses=reading.responses,
        reason=reading.reason,
    )

    _logger.info(
        "interactive_execute_complete",
        instrument=self._profile.name,
        session=session,
        outcome=driver_result.outcome,
        success=result.success,
        nudges=driver_result.nudges_sent,
        duration=f"{duration:.2f}s",
        transcript=str(transcript),
    )
    return result
health_check async
health_check()

tmux present at a supported version AND the instrument on PATH.

Source code in src/marianne/execution/instruments/interactive/backend.py
async def health_check(self) -> bool:
    """tmux present at a supported version AND the instrument on PATH."""
    if shutil.which(self._cli.command.executable) is None:
        _logger.warning(
            "interactive_health_check_failed",
            instrument=self._profile.name,
            reason="executable_not_on_path",
            executable=self._cli.command.executable,
        )
        return False
    if shutil.which("tmux") is None:
        _logger.warning(
            "interactive_health_check_failed",
            instrument=self._profile.name,
            reason="tmux_not_on_path",
        )
        return False
    version = await self._tmux.version()
    if version is None or version < MIN_TMUX_VERSION:
        _logger.warning(
            "interactive_health_check_failed",
            instrument=self._profile.name,
            reason="tmux_version_unsupported",
            found=str(version),
            minimum=".".join(str(v) for v in MIN_TMUX_VERSION),
        )
        return False
    return True

ContinuationContext dataclass

ContinuationContext(nudge_count, elapsed_seconds, screen='')

What a continuation policy may consult when the agent goes idle.

The static policy ignores this; model policies consult the idle screen.

Attributes
nudge_count instance-attribute
nudge_count

Total nudges sent so far this attempt.

elapsed_seconds instance-attribute
elapsed_seconds

Seconds since the prompt was submitted.

screen class-attribute instance-attribute
screen = ''

Last rendered idle screen, supplied as untrusted evidence.

ContinuationPolicy

Bases: Protocol

Decides what to type when the agent goes idle without finishing.

Static and model-driven policies share this contract. The driver owns the nudge budget; policies produce input or an unrecoverable decision.

Methods:
next_nudge async
next_nudge(context)

Return input or an unrecoverable signal for the idle session.

Source code in src/marianne/execution/instruments/interactive/driver.py
async def next_nudge(self, context: ContinuationContext) -> NudgeDecision:
    """Return input or an unrecoverable signal for the idle session."""
    ...

DriverResult dataclass

DriverResult(outcome, final_screen, nudges_sent, detail=None, supervisor_report=None)

Outcome of one interactive session attempt.

Attributes
outcome instance-attribute
outcome

How the attempt ended.

final_screen instance-attribute
final_screen

Last captured rendered screen (plain text). May be empty when the session died before any capture succeeded.

nudges_sent instance-attribute
nudges_sent

Total nudges delivered this attempt.

detail class-attribute instance-attribute
detail = None

Human-readable diagnostic for non-completed outcomes.

supervisor_report class-attribute instance-attribute
supervisor_report = None

Parsed instrument-supervisor forensic report for this attempt (GH #487).

Present only when the pane ran under supervise: true AND the supervisor managed to write its report before the pane teardown — an absent report is itself evidence (external kill; the supervisor never observed a forwarded signal). Never parsed from the agent's output: the report is the backend-controlled supervisor's own record.

InteractiveSessionDriver

InteractiveSessionDriver(tmux, config)

Drives one agent CLI session to completion inside tmux.

Stateless across attempts: everything attempt-specific is passed to :meth:run and lives in its locals.

Source code in src/marianne/execution/instruments/interactive/driver.py
def __init__(self, tmux: TmuxControl, config: InteractiveCliConfig) -> None:
    self._tmux = tmux
    self._config = config
    # How the last attempt's pane process ended, when tmux could say.
    self._last_pane_exit: PaneExit | None = None
Methods:
run async
run(*, session, command, cwd, prompt, marker_path, timeout_seconds, policy, max_nudges, transcript_path=None, supervisor_report_path=None, on_pane_pid=None, env=None, on_output=None)

Run one full attempt: launch, gate, submit, drive, harvest.

Parameters:

Name Type Description Default
session str

tmux session name (already sanitized, deterministic).

required
command list[str]

agent argv (executable + args), exec'd directly.

required
cwd Path

working directory for the agent (the sheet workspace).

required
prompt str

full prompt text, already carrying the completion protocol suffix that names marker_path.

required
marker_path Path

per-attempt completion marker the agent creates.

required
timeout_seconds float

overall attempt deadline.

required
policy ContinuationPolicy

continuation policy consulted on idle.

required
max_nudges int

consecutive-idle nudge budget (resets when the agent transitions back to verified-busy).

required
transcript_path Path | None

raw pipe-pane log destination (debug artifact), or None to skip transcript capture.

None
supervisor_report_path Path | None

where the instrument supervisor writes its JSON forensic report (GH #487). Read after the attempt ends; an absent/unreadable/malformed report simply means no forensics — it never fails the attempt.

None
on_pane_pid Callable[[int], None] | None

callback fired with the pane PID once known — the backend routes this to the baton's process-group registration.

None
on_output Callable[[str, bytes], None] | None

live output sink (stream_name, chunk); receives each new slice of the pipe-pane transcript on every poll so mzt watch can follow an interactive sheet (GH #381). Needs transcript_path; without a transcript there is nothing to tail.

None

Never raises TmuxError — tmux failures map to session_lost / startup_failed outcomes. CancelledError propagates (after cleanup) so musician-task cancellation works unchanged.

Source code in src/marianne/execution/instruments/interactive/driver.py
async def run(
    self,
    *,
    session: str,
    command: list[str],
    cwd: Path,
    prompt: str,
    marker_path: Path,
    timeout_seconds: float,
    policy: ContinuationPolicy,
    max_nudges: int,
    transcript_path: Path | None = None,
    supervisor_report_path: Path | None = None,
    on_pane_pid: Callable[[int], None] | None = None,
    env: dict[str, str] | None = None,
    on_output: Callable[[str, bytes], None] | None = None,
) -> DriverResult:
    """Run one full attempt: launch, gate, submit, drive, harvest.

    Args:
        session: tmux session name (already sanitized, deterministic).
        command: agent argv (executable + args), exec'd directly.
        cwd: working directory for the agent (the sheet workspace).
        prompt: full prompt text, already carrying the completion
            protocol suffix that names ``marker_path``.
        marker_path: per-attempt completion marker the agent creates.
        timeout_seconds: overall attempt deadline.
        policy: continuation policy consulted on idle.
        max_nudges: consecutive-idle nudge budget (resets when the
            agent transitions back to verified-busy).
        transcript_path: raw pipe-pane log destination (debug artifact),
            or None to skip transcript capture.
        supervisor_report_path: where the instrument supervisor writes
            its JSON forensic report (GH #487). Read after the attempt
            ends; an absent/unreadable/malformed report simply means no
            forensics — it never fails the attempt.
        on_pane_pid: callback fired with the pane PID once known —
            the backend routes this to the baton's process-group
            registration.
        on_output: live output sink ``(stream_name, chunk)``; receives
            each new slice of the pipe-pane transcript on every poll
            so ``mzt watch`` can follow an interactive sheet (GH #381).
            Needs ``transcript_path``; without a transcript there is
            nothing to tail.

    Never raises TmuxError — tmux failures map to ``session_lost`` /
    ``startup_failed`` outcomes. CancelledError propagates (after
    cleanup) so musician-task cancellation works unchanged.
    """
    if timeout_seconds <= 0:
        raise ValueError(f"timeout_seconds must be > 0, got {timeout_seconds}")
    if max_nudges < 0:
        raise ValueError(f"max_nudges must be >= 0, got {max_nudges}")

    cfg = self._config
    deadline = time.monotonic() + timeout_seconds
    last_screen = ""
    nudges_total = 0
    self._last_pane_exit = None

    try:
        # ── LAUNCH ────────────────────────────────────────────────
        # Idempotent relaunch safety: a stale same-name session from a
        # crashed prior attempt must die before we create ours.
        await self._tmux.kill_session(session)

        # A pre-existing marker (crashed prior attempt, adversarial
        # leftover) must never complete this attempt instantly.
        self._remove_marker(marker_path)

        await self._tmux.new_session(
            session,
            command,
            cwd=cwd,
            width=cfg.terminal_width,
            height=cfg.terminal_height,
            env=env,
        )

        if transcript_path is not None:
            try:
                await self._tmux.pipe_pane_to_file(session, transcript_path)
            except TmuxError as e:
                # Transcript is a debug artifact — its failure must not
                # fail the attempt.
                _logger.warning(
                    "interactive_transcript_unavailable",
                    session=session,
                    error=str(e),
                )
                transcript_path = None

        pid = await self._tmux.pane_pid(session)
        if pid is not None and on_pane_pid is not None:
            on_pane_pid(pid)

        # ── GATES → READY ─────────────────────────────────────────
        ready, last_screen = await self._await_ready(session, deadline)
        if not ready:
            return DriverResult(
                outcome="startup_failed",
                final_screen=last_screen,
                nudges_sent=0,
                detail=(
                    f"session never reached the ready prompt within "
                    f"{cfg.startup_timeout_seconds}s "
                    f"(ready_pattern={cfg.ready_pattern!r})"
                ),
            )

        # ── SUBMIT (verified — see _submit_text) ──────────────────
        await self._submit_text(session, prompt)
        submitted_at = time.monotonic()

        # ── DRIVE ─────────────────────────────────────────────────
        outcome, last_screen, nudges_total, policy_detail = await self._drive(
            session=session,
            marker_path=marker_path,
            deadline=deadline,
            submitted_at=submitted_at,
            policy=policy,
            max_nudges=max_nudges,
            transcript_path=transcript_path,
            on_output=on_output,
        )

        # ── HARVEST (exactly once — the single return below) ──────
        final_screen = (
            last_screen
            if outcome == "provider_error"
            else await self._final_screen(session, last_screen)
        )
        detail: str | None = None
        if outcome == "nudges_exhausted":
            detail = policy_detail or (
                f"agent went idle and did not complete after "
                f"{nudges_total} nudge(s)"
            )
        elif outcome == "timeout":
            detail = f"attempt deadline ({timeout_seconds}s) reached"
        elif outcome == "session_lost":
            exited = self._last_pane_exit
            supervisor_report = self._read_supervisor_report(
                supervisor_report_path,
            )
            if exited is not None:
                detail = (
                    f"agent process {exited.describe()} before signalling completion"
                )
            else:
                detail = (
                    "agent session vanished before signalling completion "
                    "(tmux no longer holds it: server gone or session killed)"
                )
            forensic = self._summarize_supervisor_forensics(
                supervisor_report,
            )
            if forensic is not None:
                detail = f"{detail}; {forensic}"
            elif supervisor_report is None:
                detail = (
                    f"{detail} (no supervisor report — "
                    "death not observed by the supervisor: external kill, "
                    "or the supervisor died first)"
                )
            else:
                # The supervisor outlived the child (it wrote the report)
                # yet forwarded nothing — the strongest external-kill
                # evidence a report can give. Do NOT call this "no
                # supervisor report": the report exists (GH #487 review).
                detail = (
                    f"{detail} (supervisor observed no forwarded signal — "
                    "death not sent by the supervisor: external kill)"
                )
            return DriverResult(
                outcome=outcome,
                final_screen=final_screen,
                nudges_sent=nudges_total,
                detail=detail,
                supervisor_report=supervisor_report,
            )
        elif outcome == "provider_error":
            detail = "interactive provider error screen detected"
        return DriverResult(
            outcome=outcome,
            final_screen=final_screen,
            nudges_sent=nudges_total,
            detail=detail,
        )

    except TmuxError as e:
        # Control-plane failure outside the drive loop (launch/submit).
        _logger.error(
            "interactive_session_control_failure",
            session=session,
            error=str(e),
            stderr=e.stderr,
        )
        return DriverResult(
            outcome="startup_failed",
            final_screen=last_screen,
            nudges_sent=nudges_total,
            detail=f"tmux control failure: {e}",
        )
    finally:
        # CLEANUP — idempotent, every exit path including cancellation.
        await self._cleanup(session)

NudgeDecision dataclass

NudgeDecision(message=None, unrecoverable=False, reason=None)

An input to send, or a reason the idle session cannot continue.

Abstain: message=None, unrecoverable=False means "nothing to send right now" — the driver re-polls without spending nudge budget; the attempt deadline still bounds the loop.

StaticNudgePolicy

StaticNudgePolicy(message=DEFAULT_NUDGE_MESSAGE)

Deterministic continuation policy: always the same message.

Source code in src/marianne/execution/instruments/interactive/driver.py
def __init__(self, message: str = DEFAULT_NUDGE_MESSAGE) -> None:
    if not message.strip():
        raise ValueError("nudge message must be non-empty")
    self._message = message
Methods:
next_nudge async
next_nudge(context)

Return the configured nudge message.

Source code in src/marianne/execution/instruments/interactive/driver.py
async def next_nudge(self, context: ContinuationContext) -> NudgeDecision:
    """Return the configured nudge message."""
    return NudgeDecision(message=self._message)

ModelNudgePolicy

ModelNudgePolicy(backend_factory, instrument_name, timeout_seconds=30.0, fallback_message=DEFAULT_NUDGE_MESSAGE)

Ask a one-off headless instrument what to type into an idle session.

The caller supplies the factory so service calls do not consume a sheet dispatch slot. Failure leaves the existing static continuation intact.

Source code in src/marianne/execution/instruments/interactive/model_nudge.py
def __init__(
    self,
    backend_factory: BackendFactory,
    instrument_name: str,
    timeout_seconds: float = 30.0,
    fallback_message: str = DEFAULT_NUDGE_MESSAGE,
) -> None:
    if not instrument_name.strip():
        raise ValueError("nudge instrument must be non-empty")
    if not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
        raise ValueError("nudge timeout must be finite and > 0")
    self._backend_factory = backend_factory
    self._instrument_name = instrument_name
    self._timeout_seconds = timeout_seconds
    self._fallback = StaticNudgePolicy(fallback_message)
Methods:
next_nudge async
next_nudge(context)

Produce bounded input; propagate cancellation after backend cleanup.

Source code in src/marianne/execution/instruments/interactive/model_nudge.py
async def next_nudge(self, context: ContinuationContext) -> NudgeDecision:
    """Produce bounded input; propagate cancellation after backend cleanup."""
    backend: Backend | None = None
    try:
        prompt = self._build_prompt(context)
        async with asyncio.timeout(self._timeout_seconds):
            backend = self._backend_factory(self._instrument_name)
            result = await backend.execute(prompt)
        if result.success:
            decision = self._parse(result.stdout or "")
            if decision is not None:
                return decision
    except Exception:  # noqa: BLE001 — model failure must not fail the attempt
        _logger.warning("interactive_model_nudge_failed_open", exc_info=True)
    finally:
        if backend is not None:
            close = getattr(backend, "close", None)
            if close is not None:
                try:
                    async with asyncio.timeout(min(self._timeout_seconds, 1.0)):
                        await close()
                except Exception:  # noqa: BLE001 — cleanup must not mask the decision
                    _logger.debug("interactive_nudge_backend_close_failed", exc_info=True)
    return await self._fallback.next_nudge(context)

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)

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