Skip to content

driver

driver

InteractiveSessionDriver — the state machine that pushes a TUI agent to done.

::

LAUNCH → GATES → READY → SUBMIT → DRIVE ⟲ → HARVEST (once) → CLEANUP

The driver owns idle handling for interactive sheets: busy detection from profile busy_patterns (primary signal), a work-area change hash that only resets the quiet clock (never alone means busy), and a nudge budget consulted through a :class:ContinuationPolicy. Completion is signalled by the agent creating a per-attempt marker file — a protocol signal, not semantic success; validations remain the authoritative arbiter downstream.

All per-attempt state lives in locals inside :meth:run — never on the instance — so BackendPool free-list reuse of the owning backend is inherently clean.

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

Classes

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.

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.

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."""
    ...

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)

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)

Functions: