Skip to content

Index

instruments

Instrument execution backends for Marianne.

This package contains config-driven backends that execute prompts through CLI instruments defined by InstrumentProfile YAML files.

The PluginCliBackend is the generic execution engine — it reads a CliProfile and builds commands, parses output, and classifies errors for any CLI tool without requiring instrument-specific Python code.

Classes

PluginCliBackend

PluginCliBackend(profile, working_directory=None)

Bases: WorkspaceMcpConfigMixin, Backend

Generic CLI backend driven by an InstrumentProfile.

Builds CLI commands, runs them via asyncio subprocess, and parses output according to the profile's output and error configuration.

This is the core of the instrument plugin system — any CLI tool with a YAML profile can be used as a mzt instrument.

Initialize from an InstrumentProfile.

Parameters:

Name Type Description Default
profile InstrumentProfile

The instrument profile describing how to invoke and parse this CLI tool.

required
working_directory Path | None

Optional working directory for subprocess.

None

Raises:

Type Description
ValueError

If the profile is not a CLI instrument.

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

    Args:
        profile: The instrument profile describing how to invoke
            and parse this CLI tool.
        working_directory: Optional working directory for subprocess.

    Raises:
        ValueError: If the profile is not a CLI instrument.
    """
    if profile.kind != "cli" or profile.cli is None:
        raise ValueError(
            f"PluginCliBackend requires kind=cli with a cli profile, "
            f"got kind={profile.kind}"
        )

    self._profile = profile
    self._cli = profile.cli
    self._working_directory: Path | None = working_directory
    self._preamble: str | None = None
    self._prompt_extensions: list[str] = []
    self._model: str | None = profile.default_model

    # #352 inc-3: per-dispatch live output sink. Set by the baton
    # adapter (hub writer) before execute(), cleared at release.
    # Receives (stream_name, chunk) per drained chunk. Exceptions
    # are swallowed — observability must never break execution.
    self._on_output: Callable[[str, bytes], None] | None = None

    # PID tracking callbacks for orphan detection.
    # Set by the daemon's ProcessGroupManager (via BackendPool) when
    # running under the conductor. Standalone CLI mode leaves these
    # as None — no orphan tracking needed.
    self._on_process_spawned: Callable[[int], None] | None = None
    self._on_process_exited: Callable[[int], None] | None = None

    # Process Lifecycle Phase 1 — group-aware callback.
    # Set by the baton adapter with (pid, pgid) at spawn time. Its
    # presence is the signal that we are on the baton path and must
    # force start_new_session=True regardless of profile setting, so
    # that deregister/cancel can kill the whole process tree.
    # See docs/specs/2026-04-16-process-lifecycle-design.md (Change 1, 3).
    self._on_process_group_spawned: Callable[[int, int], None] | None = None

    # Override tracking is shared by profile-driven executions.
    # _saved_model stores the pre-override value so clear_overrides()
    # can restore it. _has_overrides guards against double-clear.
    self._saved_model: str | None = None
    self._has_overrides: bool = False

    # MCP config path — set by callers when an MCP config is available.
    # The profile may consume it through a command flag or a temporary
    # workspace-local config file.
    self._mcp_config_path: Path | None = None

    # Opt-in structured-output schema (CLI seat). CLI profiles have no
    # profile-level default, so this slot is the direct-use setter's
    # value only; the dispatch path threads the per-sheet value
    # request-locally through SheetRequestState.
    self._response_format: dict[str, Any] | None = None

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

Human-readable backend name.

Methods:
apply_overrides
apply_overrides(overrides)

Apply per-sheet parameter overrides for the next execution.

Supports: - model: Override the default_model from the instrument profile.

Must be paired with clear_overrides() after execution. Callers MUST hold override_lock for the entire apply → execute → clear window when parallel execution is possible.

Source code in src/marianne/execution/instruments/cli_backend.py
def apply_overrides(self, overrides: dict[str, object]) -> None:
    """Apply per-sheet parameter overrides for the next execution.

    Supports:
    - ``model``: Override the default_model from the instrument profile.

    Must be paired with clear_overrides() after execution. Callers
    MUST hold override_lock for the entire apply → execute → clear
    window when parallel execution is possible.
    """
    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 original backend parameters after per-sheet execution.

Source code in src/marianne/execution/instruments/cli_backend.py
def clear_overrides(self) -> None:
    """Restore original backend parameters after per-sheet execution."""
    if self._has_overrides:
        self._model = self._saved_model
        self._saved_model = None
        self._has_overrides = False
    # W-F3: per-sheet prompt bytes never survive release into a
    # free-list-reused backend — the next sheet carries its own values
    # request-locally or via the setters, never a previous sheet's.
    self._preamble = None
    self._prompt_extensions = []
    self._response_format = None
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. clear_overrides() resets it at release.

Source code in src/marianne/execution/instruments/cli_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``. ``clear_overrides()`` resets it at release.
    """
    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. clear_overrides() resets them at release.

Source code in src/marianne/execution/instruments/cli_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``.
    ``clear_overrides()`` resets them at release.
    """
    self._prompt_extensions = list(extensions)
set_response_format
set_response_format(response_format)

Set an opt-in structured-output schema for the next execution.

Direct-use contract: the dispatch path carries the per-sheet response_format request-locally (SheetRequestState) — see Backend.set_response_format. clear_overrides() resets it at release. The value must satisfy the shared wire-contract validator (validate_openai_response_format); at execution a json_schema request additionally requires the profile's cli.command.json_schema_flag (refused loudly otherwise).

Source code in src/marianne/execution/instruments/cli_backend.py
def set_response_format(
    self, response_format: dict[str, Any] | None
) -> None:
    """Set an opt-in structured-output schema for the next execution.

    Direct-use contract: the dispatch path carries the per-sheet
    response_format request-locally (``SheetRequestState``) — see
    ``Backend.set_response_format``. ``clear_overrides()`` resets it
    at release. The value must satisfy the shared wire-contract
    validator (``validate_openai_response_format``); at execution a
    ``json_schema`` request additionally requires the profile's
    ``cli.command.json_schema_flag`` (refused loudly otherwise).
    """
    self._response_format = (
        validate_openai_response_format(response_format)
        if response_format is not None
        else None
    )
set_output_callback
set_output_callback(callback)

Set (or clear with None) the live output sink (#352 inc-3).

The callback receives (stream_name, chunk) for every chunk drained from the subprocess pipes. It runs synchronously on the event loop between pipe reads — keep it cheap and non-blocking.

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

    The callback receives ``(stream_name, chunk)`` for every chunk
    drained from the subprocess pipes. It runs synchronously on the
    event loop between pipe reads — keep it cheap and non-blocking.
    """
    self._on_output = callback
set_mcp_config
set_mcp_config(config_path)

Set path to an MCP config file.

When set, _build_command() uses the instrument's mcp_config_flag to point the CLI instrument at this config file instead of injecting mcp_disable_args. For instruments that discover MCP config through a workspace file, execute() temporarily materializes this file at mcp_config_workspace_path.

Parameters:

Name Type Description Default
config_path Path | None

Path to the MCP config JSON file, or None to clear.

required
Source code in src/marianne/execution/instruments/cli_backend.py
def set_mcp_config(self, config_path: Path | None) -> None:
    """Set path to an MCP config file.

    When set, ``_build_command()`` uses the instrument's ``mcp_config_flag``
    to point the CLI instrument at this config file instead of injecting
    ``mcp_disable_args``. For instruments that discover MCP config through
    a workspace file, ``execute()`` temporarily materializes this file at
    ``mcp_config_workspace_path``.

    Args:
        config_path: Path to the MCP config JSON file, or None to clear.
    """
    self._mcp_config_path = config_path
effort_refusal
effort_refusal(level, *, schema_mode)

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

Judged for the model this backend will run (a model row may carry its own effort_levels). Dispatch asks before spawning; _build_command asks again so a direct caller cannot bypass the profile's mapping.

Source code in src/marianne/execution/instruments/cli_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 for the model this backend will run (a model row may carry its
    own effort_levels). Dispatch asks before spawning; ``_build_command``
    asks again so a direct caller cannot bypass the profile's mapping.
    """
    return self._profile.effort_refusal(
        level, model=self._model, schema_mode=schema_mode,
    )
tools_refusal
tools_refusal(tools)

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

Source code in src/marianne/execution/instruments/cli_backend.py
def tools_refusal(self, tools: list[str]) -> str | None:
    """Why this instrument cannot run a sheet with ``tools`` (None = it can)."""
    return self._profile.tools_refusal(tools)
execute async
execute(prompt, *, timeout_seconds=None, request=None)

Execute a prompt through the CLI instrument.

Builds the command from profile config, runs it as a subprocess, and parses the output according to the profile's output config.

Parameters:

Name Type Description Default
prompt str

The prompt to execute.

required
timeout_seconds float | None

Per-execution timeout override.

None

Returns:

Type Description
ExecutionResult

ExecutionResult with parsed output and metadata.

Source code in src/marianne/execution/instruments/cli_backend.py
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
async def execute(
    self,
    prompt: str,
    *,
    timeout_seconds: float | None = None,
    request: SheetRequestState | None = None,
) -> ExecutionResult:
    """Execute a prompt through the CLI instrument.

    Builds the command from profile config, runs it as a subprocess,
    and parses the output according to the profile's output config.

    Args:
        prompt: The prompt to execute.
        timeout_seconds: Per-execution timeout override.

    Returns:
        ExecutionResult with parsed output and metadata.
    """
    guarded_binding = request.expected_route if request is not None else None

    async def reviewed_route_refusal() -> ExecutionResult | None:
        if guarded_binding is None:
            return None
        # A CLI cannot supply the HTTP backend's server model echo. Bind
        # its observable, loaded command profile and requested model
        # before launching any subprocess; downstream must retain the
        # distinction between configured execution and server attestation.
        assert request is not None
        try:
            from marianne.instruments.loader import (
                capture_resolved_instrument_route,
                route_identity,
            )

            if (guarded_binding.arm != "remote"
                    or guarded_binding.kind != "cli"
                    or self._profile._source_path is None
                    or self._profile.cli is None
                    or not self._profile.cli.command.model_flag
                    or not guarded_binding.effective_provider):
                raise ValueError("reviewed CLI route is incomplete")
            fresh = await asyncio.to_thread(
                capture_resolved_instrument_route,
                self._profile.name,
                {"model": request.route_model_override,
                 "provider": request.route_provider_override},
                now=utc_now(), arm="remote", loaded_profile=self._profile,
            )
            if (route_identity(fresh) != route_identity(guarded_binding)
                    or self._model != fresh.effective_model):
                raise ValueError("reviewed CLI route differs from current command")
            age = (utc_now() - guarded_binding.resolved_at).total_seconds()
            if not 0 <= age <= 60:
                raise ValueError("reviewed CLI route is outside the start window")
        except (OSError, ValueError) as exc:
            message = f"attempt_route_drift: {exc}"
            return ExecutionResult(
                success=False, stdout="", stderr=message,
                duration_seconds=0.0, exit_code=1,
                error_type="attempt_route_drift", error_message=message,
                model=self._model,
            )
        return None

    refusal = await reviewed_route_refusal()
    if refusal is not None:
        return refusal

    effective_timeout = timeout_seconds or self._profile.default_timeout_seconds
    first_output_bound = (
        self._cli.first_output_timeout_seconds
        if request is None or is_first_output_timeout_unset(
            request.first_output_timeout_seconds
        )
        else request.first_output_timeout_seconds
    )
    job_id = request.job_id if request is not None else None
    sheet_num = request.sheet_num if request is not None else None

    # Request-local per-sheet prompt state (W-F3): when a dispatch
    # resolved SheetRequestState, its preamble/extensions are the ONLY
    # ones this request may carry — the mutable slots (set by direct
    # setter users or a previous sheet before the release reset) must
    # not bleed into this prompt.
    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

    # Opt-in structured output (CLI seat), same tri-state contract as
    # the OpenAI-compatible backend: the dispatch-resolved request
    # value wins unless UNSET; explicit None opts out of the
    # direct-setter default. The resolved value is request-local —
    # the shared pooled singleton's mutable slot is never read when a
    # request is in hand, so no concurrent sheet's schema can leak.
    response_format: dict[str, Any] | None
    if request is not None:
        requested = request.response_format
        if isinstance(requested, _ResponseFormatUnset):
            response_format = self._response_format
        else:
            response_format = requested
    else:
        response_format = self._response_format

    # GH#188: Force stdin delivery when the assembled prompt is large.
    # CLI tools crash when receiving 100KB+ prompts as positional
    # arguments. Marianne prompts routinely exceed this with
    # cadenza/prelude injection. 32KB is a conservative threshold.
    full_prompt_for_size = self._build_prompt(
        prompt, req_preamble, req_extensions
    )
    use_stdin = self._cli.command.prompt_via_stdin
    prompt_bytes = len(full_prompt_for_size.encode("utf-8"))
    if not use_stdin and prompt_bytes > 32_768:
        can_force_stdin = self._cli.command.stdin_sentinel is not None
        if can_force_stdin:
            _logger.info(
                "plugin_cli_stdin_forced",
                instrument=self._profile.name,
                prompt_bytes=prompt_bytes,
                reason="prompt exceeds 32KB safe limit for CLI arguments",
            )
            use_stdin = True
        else:
            _logger.warning(
                "plugin_cli_stdin_not_supported_for_large_prompt",
                instrument=self._profile.name,
                prompt_bytes=prompt_bytes,
                reason=(
                    "profile has no stdin sentinel; keeping prompt in "
                    "argv to avoid launching the CLI with no prompt"
                ),
            )

    cmd = self._build_command(
        prompt, timeout_seconds=effective_timeout,
        force_stdin=use_stdin and not self._cli.command.prompt_via_stdin,
        preamble=req_preamble,
        prompt_extensions=req_extensions,
        response_format=response_format,
        effort=request.effort if request is not None else None,
        tools=request.tools if request is not None else None,
    )
    if guarded_binding is not None:
        model_flag = self._cli.command.model_flag
        assert model_flag is not None
        positions = [i for i, item in enumerate(cmd) if item == model_flag]
        if (len(positions) != 1 or positions[0] + 1 >= len(cmd)
                or cmd[positions[0] + 1] != guarded_binding.effective_model):
            message = "attempt_route_drift: CLI command does not select reviewed model"
            return ExecutionResult(
                success=False, stdout="", stderr=message,
                duration_seconds=0.0, exit_code=1,
                error_type="attempt_route_drift", error_message=message,
                model=self._model,
            )
    env = self._scratch_env(self._build_env(), sheet_num=sheet_num)

    _logger.info(
        "plugin_cli_execute_start",
        instrument=self._profile.name,
        executable=cmd[0],
        prompt_length=len(prompt),
        timeout=effective_timeout,
        stdin_mode=use_stdin,
    )

    start_time = time.monotonic()
    stdout_data = ""
    stderr_data = ""
    exit_code: int | None = None
    exit_reason = "completed"
    spawn_error_type: str | None = None  # GH #418: typed route-unavailable cause
    returncode_at_timeout: int | None = None
    post_exit_grace_fired = False
    stdout_chunks: list[bytes] = []
    stderr_chunks: list[bytes] = []
    proc: asyncio.subprocess.Process | None = None
    pgid: int | None = None
    workspace_mcp_target = self._workspace_mcp_config_target()
    workspace_mcp_lock: asyncio.Lock | None = None
    workspace_mcp_lock_acquired = False
    workspace_mcp_restore: tuple[Path, bytes | None, bool, int | None] | None = None

    # Process Lifecycle Phase 1: presence of the group-aware callback is
    # our signal that we are on the baton path. When set, force
    # start_new_session=True regardless of profile so the whole
    # subprocess tree (including pytest workers) is in a killable group.
    _baton_path = self._on_process_group_spawned is not None
    _force_new_session = (
        True if _baton_path else self._cli.command.start_new_session
    )

    try:
        if workspace_mcp_target is not None:
            lock_key = workspace_mcp_target.resolve()
            workspace_mcp_lock = _MCP_WORKSPACE_CONFIG_LOCKS.setdefault(
                lock_key,
                asyncio.Lock(),
            )
            await workspace_mcp_lock.acquire()
            workspace_mcp_lock_acquired = True

        # Resolve executable to full path to avoid FileNotFoundError
        # in daemon contexts where asyncio's posix_spawn may fail to
        # resolve executables even though they exist on PATH.
        import shutil as _shutil
        _resolved = _shutil.which(cmd[0])
        if _resolved:
            cmd = [_resolved] + cmd[1:]
        # Every descendant of the instrument dies with the attempt: the
        # supervisor is a subreaper in the instrument's own group, so a
        # grandchild whose parent exits re-parents to it, not to init.
        # Only a RESOLVED executable is wrapped: an absent binary must
        # still surface as this spawn's FileNotFoundError (the typed
        # executable_not_found route, GH #418), not as the supervisor's
        # own exit 127.
        if self._cli.command.supervise and _resolved:
            cmd = supervised_argv(
                cmd, io_priority=self._cli.command.io_priority,
                max_open_files=self._cli.command.max_open_files,
            )

        # Ensure working directory exists before spawning —
        # asyncio.create_subprocess_exec raises FileNotFoundError
        # for both missing executables AND missing cwd, so we
        # must ensure cwd exists to disambiguate errors.
        if self._working_directory and not self._working_directory.exists():
            self._working_directory.mkdir(parents=True, exist_ok=True)

        if workspace_mcp_target is not None:
            workspace_mcp_restore = self._materialize_workspace_mcp_config(
                workspace_mcp_target,
            )

        # Preparation includes an awaited workspace lock. Re-resolve the
        # exact reviewed profile and start window after that work, at the
        # actual spawn boundary rather than only at execute() entry.
        refusal = await reviewed_route_refusal()
        if refusal is not None:
            return refusal

        proc = await asyncio.create_subprocess_exec(
            *cmd,
            stdin=asyncio.subprocess.PIPE if use_stdin else None,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            cwd=str(self._working_directory) if self._working_directory else None,
            env=env,
            start_new_session=_force_new_session,
        )
        # GH #446: the kernel start tick is the identity; the float is
        # the non-Linux fallback (it drifts with every clock correction).
        parent_create_time, parent_start_ticks = spawn_identity(proc.pid)
        pipe_inodes: set[int] = set()
        for stream in (proc.stdout, proc.stderr):
            if not isinstance(stream, asyncio.StreamReader):
                continue
            transport = getattr(stream, "_transport", None)
            pipe = transport.get_extra_info("pipe") if transport else None
            if pipe is not None:
                try:
                    pipe_inodes.add(os.fstat(pipe.fileno()).st_ino)
                except (OSError, ValueError):
                    pass

        # Capture pgid at spawn — never re-derive from proc.pid later.
        # See docs/specs/2026-04-16-process-lifecycle-design.md (Change 1).
        # Only when the child got its OWN group: without
        # start_new_session, getpgid returns OUR group, and kill-on-exit
        # would be guard-refused and hang forever awaiting a process
        # nobody killed (#376). pgid=None routes to proc.kill() instead.
        if _force_new_session and proc.pid is not None:
            try:
                pgid = os.getpgid(proc.pid)
            except ProcessLookupError:
                # The parent may have exited while children retain its group.
                pgid = proc.pid

        # Daemon-own-group safety: never kill the daemon's own group.
        # If start_new_session failed or the kernel ignored it, abort
        # the spawn rather than risk killing ourselves in the finally.
        if _baton_path and pgid is not None:
            try:
                daemon_pgid = os.getpgid(0)
            except ProcessLookupError:
                daemon_pgid = None
            if daemon_pgid is not None and pgid == daemon_pgid:
                try:
                    proc.kill()
                except ProcessLookupError:
                    pass
                try:
                    await proc.wait()
                except ProcessLookupError:
                    pass
                raise RuntimeError(
                    f"Spawned process shares daemon pgid ({pgid}); "
                    "refusing to continue"
                )

        # Track PID for orphan detection by the daemon's pgroup manager
        if self._on_process_spawned and proc.pid is not None:
            self._on_process_spawned(proc.pid)

        # Fire the group-aware callback (baton adapter records pid+pgid
        # in _active_pids so deregister/cancel can killpg the tree).
        if (
            self._on_process_group_spawned is not None
            and proc.pid is not None
            and pgid is not None
        ):
            self._on_process_group_spawned(proc.pid, pgid)

        # When using stdin mode, write the assembled prompt to the
        # subprocess stdin and close it to signal EOF. This must
        # happen before draining the output pipes — if the subprocess
        # waits for stdin EOF before producing output, reading stdout
        # first would deadlock.
        if use_stdin and proc.stdin is not None:
            full_prompt = self._build_prompt(
                prompt, req_preamble, req_extensions
            )
            proc.stdin.write(self._encode_stdin_prompt(full_prompt))
            await proc.stdin.drain()
            proc.stdin.close()

        # Drain both pipes concurrently. Observe the direct parent's
        # returncode independently of pipe EOF, then bound remaining
        # reads by the profile's post-exit grace. Decode after capture.
        descendants: dict[int, DescendantIdentity] = {}

        def _capture_descendants() -> None:
            if proc.pid is not None and parent_create_time is not None:
                descendants.update((child.pid, child)
                                   for child in snapshot_descendant_trees(
                                       proc.pid, parent_create_time,
                                       parent_start_ticks=parent_start_ticks))

        def _safe_emit(stream_name: str) -> Callable[[bytes], None]:
            callback = self._on_output

            def emit(chunk: bytes) -> None:
                # A short-lived CLI can print its child PID and exit
                # before the parent-exit poll gets another turn.
                _capture_descendants()
                if callback is None:
                    return
                try:
                    callback(stream_name, chunk)
                except Exception:  # noqa: BLE001 — structured logger reports plugin_cli_output_callback_failed
                    _logger.debug(
                        "plugin_cli_output_callback_failed",
                        instrument=self._profile.name,
                        stream=stream_name,
                    )

            return emit

        drains = [
            asyncio.create_task(_drain_stream(
                proc.stdout, stdout_chunks, on_chunk=_safe_emit("stdout"),
            )),
            asyncio.create_task(_drain_stream(
                proc.stderr, stderr_chunks, on_chunk=_safe_emit("stderr"),
            )),
        ]
        first_output_stall = False
        try:
            try:
                exit_code = await self._wait_bounded_by_first_output(
                    proc, descendants, parent_create_time, parent_start_ticks,
                    effective_timeout, first_output_bound, stdout_chunks, stderr_chunks,
                )
                if parent_create_time is not None:
                    descendants.update((child.pid, child) for child in
                                       snapshot_pipe_holders(
                                           frozenset(pipe_inodes),
                                           parent_create_time,
                                       ))
                try:
                    await asyncio.wait_for(
                        asyncio.gather(*drains),
                        timeout=self._cli.post_exit_drain_grace_seconds,
                    )
                except TimeoutError:
                    post_exit_grace_fired = True
                    returncode_at_timeout = exit_code
            except _FirstOutputStall:
                # GH #434: zero bytes for first_output_timeout_seconds is a
                # dead session at start, not thinking. End it NOW as a
                # timeout carrying the stale marker so the classifier
                # files it as EXECUTION_STALE (120 s retry, then fallback)
                # instead of the whole sheet timeout reading as success
                # for whoever played next.
                first_output_stall = True
                returncode_at_timeout = proc.returncode
                _logger.warning(
                    "plugin_cli_first_output_stall",
                    instrument=self._profile.name,
                    first_output_timeout=first_output_bound,
                    timeout=effective_timeout,
                    job_id=job_id,
                    sheet_num=sheet_num,
                    returncode_at_timeout=returncode_at_timeout,
                )
                exit_reason = "timeout"
            except TimeoutError:
                returncode_at_timeout = proc.returncode
                _logger.warning(
                    "plugin_cli_timeout",
                    instrument=self._profile.name,
                    timeout=effective_timeout,
                    job_id=job_id,
                    sheet_num=sheet_num,
                    returncode_at_timeout=returncode_at_timeout,
                    stdout_bytes=sum(map(len, stdout_chunks)),
                    stderr_bytes=sum(map(len, stderr_chunks)),
                    post_exit_grace_fired=post_exit_grace_fired,
                )
                exit_reason = "timeout"
        finally:
            for drain in drains:
                if not drain.done():
                    drain.cancel()
            await asyncio.gather(*drains, return_exceptions=True)
            # Kill-on-exit: clean exits are a noop unless the grace
            # expired with a surviving pipe owner. Timeouts and
            # cancellation retain SIGTERM -> grace -> SIGKILL.
            await _kill_process_group_if_alive(
                proc, pgid, reap_exited_group=post_exit_grace_fired,
            )
            reaped = reap_descendant_trees(tuple(descendants.values()))
            _logger.info(
                "plugin_cli_descendants_reaped",
                instrument=self._profile.name,
                job_id=job_id,
                sheet_num=sheet_num,
                signalled=reaped.signalled,
                already_gone=reaped.already_gone,
                skipped_identity_mismatch=reaped.skipped_identity_mismatch,
                skipped_unsafe_group=reaped.skipped_unsafe_group,
            )
            # Decode AFTER the try so partial output survives timeout
            # and cancellation — the drain appends chunks in place
            # precisely so the cancelled gather can't discard them,
            # and a timing-out sheet's last words are the diagnostic
            # payload. exit_code stays clean-completion-only: after
            # the kill above, proc.returncode is OUR signal, not the
            # agent's exit.
            stdout_data = b"".join(stdout_chunks).decode(
                "utf-8", errors="replace"
            )
            stderr_data = b"".join(stderr_chunks).decode(
                "utf-8", errors="replace"
            )
            if first_output_stall:
                # The classifier keys EXECUTION_STALE on this marker
                # (core/errors/classifier.py, F-097); it is the only
                # text a zero-byte session has.
                stderr_data += (
                    f"\nStale execution: no output within "
                    f"{first_output_bound:g}s of start "
                    "(first_output_timeout_seconds, GH #434)\n"
                )

    except FileNotFoundError:
        # After ensuring cwd exists above, this is genuinely about
        # a missing executable, not a missing working directory.
        stderr_data = f"Executable not found: {cmd[0]}"
        exit_reason = "error"
        spawn_error_type = "executable_not_found"
        _logger.error(
            "plugin_cli_executable_not_found",
            instrument=self._profile.name,
            executable=cmd[0],
        )
    except OSError as e:
        stderr_data = f"Failed to start process: {e}"
        if getattr(e, "errno", None) == errno.E2BIG:
            # The route is installed and fine; the PROMPT does not fit
            # argv (kernel per-argument cap). Say so, or status reads
            # as if the binary were missing (GH #450 gap 3).
            stderr_data = (
                f"Failed to start process: {e} — the prompt exceeds the "
                "kernel argv limit for a profile that passes it in argv "
                "(prompt_via_stdin: false); use stdin delivery"
            )
        exit_reason = "error"
        spawn_error_type = "spawn_failed"
        _logger.error(
            "plugin_cli_execution_error",
            instrument=self._profile.name,
            error=str(e),
        )
    finally:
        if workspace_mcp_restore is not None:
            self._restore_workspace_mcp_config(workspace_mcp_restore)
        if workspace_mcp_lock is not None and workspace_mcp_lock_acquired:
            workspace_mcp_lock.release()

    # Untrack PID — process and children are cleaned up
    if self._on_process_exited and proc is not None and proc.pid is not None:
        self._on_process_exited(proc.pid)

    duration = time.monotonic() - start_time

    # Parse the output
    result = self._parse_output(
        stdout_data, stderr_data, exit_code=exit_code,
        response_format=response_format,
    )
    if guarded_binding is not None:
        result.model_requested = guarded_binding.effective_model

    # Override fields that _parse_output doesn't set
    result.duration_seconds = duration
    if exit_reason == "timeout":
        result.success = False
        result.exit_reason = "timeout"
    elif exit_reason == "error":
        result.success = False
        result.exit_reason = "error"
        if spawn_error_type is not None:
            # The route itself could not be reached (binary absent /
            # spawn refused). Typed so the baton's INSTRUMENT_UNAVAILABLE
            # bucket keys on this, never on stderr text (GH #418).
            result.error_type = spawn_error_type

    _logger.info(
        "plugin_cli_execute_complete",
        instrument=self._profile.name,
        job_id=job_id,
        sheet_num=sheet_num,
        returncode_at_timeout=returncode_at_timeout,
        stdout_bytes=sum(map(len, stdout_chunks)),
        stderr_bytes=sum(map(len, stderr_chunks)),
        post_exit_grace_fired=post_exit_grace_fired,
        success=result.success,
        duration=f"{duration:.2f}s",
        exit_code=exit_code,
        rate_limited=result.rate_limited,
    )

    if result.rate_limited:
        _logger.info(
            "plugin_cli_rate_limit_detected",
            instrument=self._profile.name,
            exit_code=exit_code,
            stdout_head=stdout_data[:1000] if stdout_data else "",
            stderr_head=stderr_data[:1000] if stderr_data else "",
            error_type=result.error_type,
            error_message=result.error_message,
        )

    return result
health_check async
health_check()

Check if the CLI instrument is available.

Verifies the executable exists on PATH. Does not run a test prompt — that would consume API quota.

Returns:

Type Description
bool

True if the executable is found on PATH.

Source code in src/marianne/execution/instruments/cli_backend.py
async def health_check(self) -> bool:
    """Check if the CLI instrument is available.

    Verifies the executable exists on PATH. Does not run a test
    prompt — that would consume API quota.

    Returns:
        True if the executable is found on PATH.
    """
    executable = self._cli.command.executable
    found = shutil.which(executable) is not None

    if not found:
        _logger.warning(
            "plugin_cli_health_check_failed",
            instrument=self._profile.name,
            executable=executable,
            reason="not_on_path",
        )

    return found