diff --git a/abstractcore/tools/command_verdict.py b/abstractcore/tools/command_verdict.py new file mode 100644 index 00000000..e34c5925 --- /dev/null +++ b/abstractcore/tools/command_verdict.py @@ -0,0 +1,83 @@ +"""How a finished shell command is reported, shared by `execute_command` and `shell_exec`. + +The verdict comes from the exit code alone: the command's output is never scanned (no text +heuristics). A failing command usually says why at the END of its output (the compiler's last +error, the test summary), so a long failing output keeps its head AND its tail in the preview. +""" + +from __future__ import annotations + +import signal +from typing import Tuple + +NO_PIPEFAIL_NOTE = ( + "Note: this shell has no pipefail; a pipeline's exit code is its last command's only, " + "so an earlier failing stage is not reported." +) +UNKNOWN_PIPEFAIL_NOTE = ( + "Note: whether this shell has pipefail is unknown (its check did not finish); an earlier " + "failing pipeline stage may not be reported." +) + +_SIGPIPE = int(getattr(signal, "SIGPIPE", 13)) + + +def command_failure_sentence(return_code: int) -> str: + """The failure verdict of a non-zero exit. 141 = 128 + SIGPIPE; a negative code is a + signal that killed the shell itself.""" + sentence = f"Command failed (exit code {return_code})" + if return_code in (128 + _SIGPIPE, -_SIGPIPE): + return ( + f"{sentence}. This is the code of a process killed by SIGPIPE, which usually means it " + "was writing to a pipe whose reader stopped early (for example `head` or `grep -q`), " + "so it was cut off before finishing; rerun without that stage if its completion matters." + ) + return sentence + _signal_suffix(return_code) + + +def _signal_suffix(return_code) -> str: + if return_code is None or return_code >= 0: + return "" + try: + name = signal.Signals(-return_code).name + except Exception: + name = f"signal {-return_code}" + return f": terminated by {name}" + + +UNREADABLE_EXIT_CODE_SENTENCE = ( + "Command failed: its exit code could not be read, so it is not reported as a success" +) + + +def session_ended_sentence(return_code, *, not_run: bool = False) -> str: + """The failure verdict when a command ended the persistent shell itself (`exit`, `set -e` + then a failing command, a sourced script that exits). `not_run`: the shell ended before + this command, while the previous one, which had timed out, was being interrupted. The + interrupt may have ended it (the command had `exec`ed over the shell, or an INT trap + exits), it may have exited by itself in that moment, or another thread closed the session: + these cannot be told apart, so the sentence claims none of them.""" + code = "unknown" if return_code is None else str(return_code) + status = f"(exit code {code}{_signal_suffix(return_code)})" + lost = "its state (working directory, environment, background jobs) is lost and the next call starts a new session" + if not_run: + return ( + "The shell session ended while the previous command, which had timed out, was being interrupted " + f"{status}; this command was not run; {lost}" + ) + return f"The shell session ended during this command {status}; {lost}" + + +def join_head_and_tail(head: str, tail: str, omitted: int) -> str: + return f"{head}\n... ({omitted} chars omitted) ...\n{tail}" + + +def head_and_tail(text: str, *, limit: int) -> Tuple[str, bool]: + """``(preview, truncated)``: ``text`` itself when it fits, else its first quarter-budget and + its last three-quarter-budget with the omitted count between them.""" + s = "" if text is None else str(text) + if limit <= 0 or len(s) <= limit: + return s, False + head_n = limit // 4 + tail_n = limit - head_n + return join_head_and_tail(s[:head_n], s[-tail_n:], len(s) - head_n - tail_n), True diff --git a/abstractcore/tools/common_tools.py b/abstractcore/tools/common_tools.py index 425e9367..ada749c8 100644 --- a/abstractcore/tools/common_tools.py +++ b/abstractcore/tools/common_tools.py @@ -13451,35 +13451,76 @@ def _idempotent_insert_replace_exact( # work belongs in a background process the caller polls. EXECUTE_COMMAND_MAX_TIMEOUT_S = 600.0 +# One verdict for execute_command and shell_exec (exit code only, output never scanned). +from .command_verdict import NO_PIPEFAIL_NOTE as _NO_PIPEFAIL_NOTE # noqa: E402 +from .command_verdict import command_failure_sentence as _command_failure_sentence # noqa: E402 +from .command_verdict import head_and_tail as _head_and_tail # noqa: E402 + + +def _execute_command_guidance(os_name: str) -> Dict[str, Any]: + """What the model is told about `execute_command` (description, when_to_use, examples) on + the platform the command runs on, chosen the way the tool chooses its shell (`os.name`): + a POSIX shell with pipefail on macOS and Linux, else `cmd.exe`, which has no pipefail and + none of the POSIX grouping syntax. Every sentence must be true where it is shown.""" + if os_name == "posix": + return { + "description": "Run a shell command; pipelines use pipefail, so any failing stage fails the command and the result gives the real exit code with stdout and stderr.", + "when_to_use": "Output is already previewed: never pipe into head (it cuts the command off). Keep grep tests in a group so cmd's failure still counts: cmd | { grep pat || [ $? -eq 1 ]; } allows no match; cmd | { grep pat >/dev/null && echo y || echo n; }", + "examples": [ + { + "description": "List current directory contents", + "arguments": { + "command": "ls -la" + } + }, + { + "description": "Filter a build's errors: a failing build still fails the command, no match is fine, no `| head` needed", + "arguments": { + "command": "cargo build 2>&1 | { grep -E '^error' -A 7 || [ $? -eq 1 ]; }" + } + }, + { + "description": "Safe mode with confirmation", + "arguments": { + "command": "rm temp_file.txt", + "require_confirmation": True + } + } + ], + } + return { + "description": "Run a command in cmd.exe; the result gives its exit code with stdout and stderr. A pipeline (a | b) reports only its last command's exit code, so a failing earlier stage is not reported.", + "when_to_use": "Output is already previewed, so do not pipe it into more or findstr to shorten it. Run a command whose failure matters on its own: after build | findstr error the exit code is findstr's (0 on a match, 1 on none), not the build's.", + "examples": [ + { + "description": "List current directory contents", + "arguments": { + "command": "dir" + } + }, + { + "description": "Run a build on its own, so a failing build fails the command (piped into findstr, only findstr's exit code would be reported)", + "arguments": { + "command": "cargo build 2>&1" + } + }, + { + "description": "Safe mode with confirmation", + "arguments": { + "command": "del temp_file.txt", + "require_confirmation": True + } + } + ], + } + @tool( - description="Execute shell commands safely with security controls and platform detection", - when_to_use="When you need to run system commands, shell scripts, or interact with command-line tools", + **_execute_command_guidance(os.name), tags=["mutating"], # Round 12: the host stamps the run's workspace set here (paths only); the command runs # inside the OS sandbox built from it (abstractcore.tools.sandbox). Never model-facing. hide_args=["_sandbox"], - examples=[ - { - "description": "List current directory contents", - "arguments": { - "command": "ls -la" - } - }, - { - "description": "Search for a pattern in files (grep)", - "arguments": { - "command": "grep -R \"ActiveContextPolicy\" -n abstractruntime/src/abstractruntime | head" - } - }, - { - "description": "Safe mode with confirmation", - "arguments": { - "command": "rm temp_file.txt", - "require_confirmation": True - } - } - ] ) def execute_command( command: str, @@ -13499,6 +13540,27 @@ def execute_command( cannot sandbox it the command is refused (success=False, one sentence) unless the host allowed unsandboxed commands. + On POSIX a string command runs with pipefail (``/bin/sh -o pipefail -c`` when that shell + supports it, else ``bash --posix -o pipefail -c``; the ``pipefail`` result field says + whether pipefail is on), so a pipeline fails when any stage fails: + ``cargo build 2>&1 | grep error`` reports cargo's exit code, and ``grep`` finding nothing + exits 1. Keep grep tests inside a group so the producer's failure still counts: + ``cmd | { grep pat || [ $? -eq 1 ]; }`` accepts no match (grep's own errors, exit 2, still + fail), and ``cmd | { grep pat >/dev/null && echo yes || echo no; }`` tests for a match. + Ungrouped, ``cmd | grep pat || true`` and ``cmd | grep pat >/dev/null && echo yes || echo + no`` hide cmd's failure, and ``cmd | grep -q pat`` can fail with 141 when grep stops reading before cmd is done. + A non-zero exit is ``success=False`` with "Command failed (exit code N)" and the full + stdout/stderr (a long failing output keeps its head AND its tail in the preview); exit 141 + is a process killed by SIGPIPE, usually cut off by a stage such as ``head`` that stopped + reading. Output is already captured, previewed and kept in full by the tool, so piping + into ``head`` to shorten it is unnecessary. + + On Windows the command runs in ``cmd.exe``, which has no pipefail: a pipeline reports its + last command's exit code, ``pipefail`` is false and every finished command's result says so + (a timed-out one has no exit code to qualify). The description, + when_to_use and examples the model reads are the ones for the platform the tool runs on + (``_execute_command_guidance``). + Args: command: The shell command to execute working_directory: Directory to run the command in (default: current directory) @@ -13675,7 +13737,7 @@ def _drained_text(value: Any) -> Optional[str]: working_dir = None # Round 12: the OS sandbox this command runs inside (never a parse of the command). - from .sandbox import KIND_UNSANDBOXED, refusal_result, sandbox_for_tool_call + from .sandbox import KIND_UNSANDBOXED, posix_shell, refusal_result, sandbox_for_tool_call sandbox = sandbox_for_tool_call(_sandbox) if sandbox.refuses: @@ -13687,12 +13749,18 @@ def _drained_text(value: Any) -> Optional[str]: ) # Library use with no workspace policy keeps the historical behaviour byte for byte. report_sandbox = sandbox.spec is not None or sandbox.kind != KIND_UNSANDBOXED + # POSIX string commands run with pipefail (any failing pipeline stage fails the + # command), sandboxed or not; the same cached shell choice backs sandbox.wrap. The + # result reports whether this shell had it. Windows keeps cmd.exe via shell=True. + # Resolved ONCE for this call, so the argv and the reported field always agree. + is_posix = os.name == "posix" + shell_prefix, pipefail = posix_shell() if is_posix else ((), False) if sandbox.kind == KIND_UNSANDBOXED: - popen_cmd: Any = command - popen_shell = True + popen_cmd: Any = (list(shell_prefix) + [command]) if is_posix else command + popen_shell = not is_posix popen_env = sandbox.env_for() if sandbox.spec is not None else None else: - popen_cmd, popen_env = sandbox.wrap(command, str(working_dir) if working_dir else None) + popen_cmd, popen_env = sandbox.wrap(command, str(working_dir) if working_dir else None, shell=shell_prefix) popen_shell = False sandbox_fields: Dict[str, Any] = {"sandbox": sandbox.describe()} if report_sandbox else {} @@ -13781,6 +13849,9 @@ def _drained_text(value: Any) -> Optional[str]: # The command finished, but inside a SHORTER window than the # caller asked for β€” say so here too, not only on timeouts. output_parts.append(timeout_clamp_note) + if not pipefail: + # Also on Windows: cmd.exe has no pipefail, and the model must read that there too. + output_parts.append(_NO_PIPEFAIL_NOTE) stdout_full = result.stdout or "" stderr_full = result.stderr or "" @@ -13790,31 +13861,43 @@ def _drained_text(value: Any) -> Optional[str]: stdout_truncated = False stderr_truncated = False + failed = result.returncode != 0 + if capture_output: if stdout_full: # Keep the rendered preview bounded for LLM usability. Full output is still returned # in structured fields so higher layers can store it durably as evidence. - stdout_preview, stdout_truncated = _truncate(stdout_full, limit=20000) - if stdout_truncated: - stdout_preview += f"\n... (output truncated, {len(stdout_full)} total chars)" + if failed: + stdout_preview, stdout_truncated = _head_and_tail(stdout_full, limit=20000) + else: + stdout_preview, stdout_truncated = _truncate(stdout_full, limit=20000) + if stdout_truncated: + stdout_preview += f"\n... (output truncated, {len(stdout_full)} total chars)" output_parts.append(f"\nπŸ“€ STDOUT:\n{stdout_preview}") if stderr_full: - stderr_preview, stderr_truncated = _truncate(stderr_full, limit=5000) - if stderr_truncated: - stderr_preview += f"\n... (error output truncated, {len(stderr_full)} total chars)" + if failed: + stderr_preview, stderr_truncated = _head_and_tail(stderr_full, limit=5000) + else: + stderr_preview, stderr_truncated = _truncate(stderr_full, limit=5000) + if stderr_truncated: + stderr_preview += f"\n... (error output truncated, {len(stderr_full)} total chars)" output_parts.append(f"\n❌ STDERR:\n{stderr_preview}") - if result.returncode == 0: + if not failed: output_parts.append("\nβœ… Command completed successfully") else: - output_parts.append(f"\n⚠️ Command completed with non-zero exit code: {result.returncode}") + if not stdout_full and not stderr_full: + output_parts.append("\n(no output)") + output_parts.append(f"\n❌ {_command_failure_sentence(int(result.returncode))}") else: output_parts.append("πŸ“ Output capture disabled") + if result.returncode != 0: + output_parts.append(f"❌ {_command_failure_sentence(int(result.returncode))}") rendered = "\n".join(output_parts) ok = bool(result.returncode == 0) - err = None if ok else f"Command completed with non-zero exit code: {int(result.returncode)}" + err = None if ok else _command_failure_sentence(int(result.returncode)) return { "success": ok, "error": err, @@ -13829,6 +13912,7 @@ def _drained_text(value: Any) -> Optional[str]: "stderr_preview": stderr_preview, "stdout_truncated": bool(stdout_truncated), "stderr_truncated": bool(stderr_truncated), + "pipefail": bool(pipefail), "rendered": rendered, **sandbox_fields, } @@ -13913,6 +13997,7 @@ def _drained_text(value: Any) -> Optional[str]: "stderr_preview": stderr_preview, "stdout_truncated": bool(stdout_truncated), "stderr_truncated": bool(stderr_truncated), + "pipefail": bool(pipefail), "rendered": rendered, **sandbox_fields, } diff --git a/abstractcore/tools/sandbox.py b/abstractcore/tools/sandbox.py index 7ab34d18..8d2392eb 100644 --- a/abstractcore/tools/sandbox.py +++ b/abstractcore/tools/sandbox.py @@ -952,13 +952,91 @@ def _windows_python() -> str: Command = Union[str, Sequence[str]] +# -------------------------------------------------------------------------------------- +# The shell a string command runs in +# -------------------------------------------------------------------------------------- + +# A pipeline's exit status is its LAST stage's without pipefail: `cargo build 2>&1 | grep +# error | head` exited 0 while the build failed, and the tool reported success (2026-11-17). +# String commands therefore run with pipefail: in /bin/sh itself when it honours the option +# (macOS /bin/sh is bash in POSIX mode; Ubuntu's dash 0.5.12 and busybox ash have it), so each +# platform keeps its own /bin/sh semantics; else in `bash --posix` (older dash lacks it). +# Neither reads a startup file for `-c`: /bin/sh and `--posix` never source $BASH_ENV (plain +# `bash -c` does), and $ENV is only read by interactive shells. The caller reports the answer. +_BASH_CANDIDATES: Tuple[str, ...] = ("/bin/bash", "/usr/bin/bash") +_POSIX_SH = "/bin/sh" +_SHELL_LOCK = threading.Lock() +_SHELL: Optional[Tuple[Tuple[str, ...], bool]] = None + + +def _honours_pipefail(shell_argv: Sequence[str]) -> Optional[bool]: + """True when ``shell_argv + ["false | true"]`` exits 1: the option is accepted AND the + failing first stage decides the status (an unknown option exits 2 in dash). None when + the probe gave no answer (it could not run, timed out, or a signal killed it): nothing + to cache.""" + import subprocess + + try: + done = subprocess.run( + list(shell_argv) + ["false | true"], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + ) + except Exception: + return None + if done.returncode < 0: + return None + return done.returncode == 1 + + +def _resolve_posix_shell() -> Tuple[Tuple[Tuple[str, ...], bool], bool]: + """``((argv prefix, pipefail), conclusive)``. Not conclusive when a probe that could have + changed the choice gave no answer: the caller uses the answer for this call and probes + again next time.""" + conclusive = True + candidates = [(_POSIX_SH, "-o", "pipefail", "-c")] + candidates += [(bash, "--posix", "-o", "pipefail", "-c") for bash in _BASH_CANDIDATES if os.path.isfile(bash) and os.access(bash, os.X_OK)] + for argv in candidates: + ok = _honours_pipefail(argv) + if ok: + return (argv, True), conclusive + if ok is None: + conclusive = False + return ((_POSIX_SH, "-c"), False), conclusive + + +def posix_shell() -> Tuple[Tuple[str, ...], bool]: + """``(argv prefix ending in "-c", pipefail)`` for a POSIX string command. Resolved once + per process (one probe run per candidate, then cached); never probed per call. A probe + that raised is not an answer: that resolution is used once and not cached.""" + global _SHELL + if _SHELL is None: + with _SHELL_LOCK: + if _SHELL is None: + choice, conclusive = _resolve_posix_shell() + if not conclusive: + return choice + _SHELL = choice + return _SHELL + + +def _reset_posix_shell_for_tests() -> None: + global _SHELL + with _SHELL_LOCK: + _SHELL = None + + @dataclass(frozen=True) class Sandbox: kind: str spec: Optional[SandboxSpec] reason: str = "" # why commands are refused (kind none) _prefix: Tuple[str, ...] = () - _shell: Tuple[str, ...] = ("/bin/sh", "-c") # what runs a command given as one string + # What runs a command given as one string, when the sandbox brings its own (Windows: the + # launcher's --shell). None: the POSIX shell wrap() resolves (pipefail when available). + _shell: Optional[Tuple[str, ...]] = None _exec: Tuple[str, ...] = () # what introduces a command given as a list # Drives this sandbox reads and writes as the user can (Windows: no access lists, a # network share), each with its sentence; shown wherever writes would be limited. @@ -1026,15 +1104,29 @@ def env_for(self, env: Optional[Mapping[str, str]] = None) -> Dict[str, str]: base[key] = tmp return base - def wrap(self, command: Command, cwd: Optional[str] = None, env: Optional[Mapping[str, str]] = None) -> Tuple[List[str], Dict[str, str]]: + def wrap( + self, + command: Command, + cwd: Optional[str] = None, + env: Optional[Mapping[str, str]] = None, + *, + shell: Optional[Sequence[str]] = None, + ) -> Tuple[List[str], Dict[str, str]]: """(argv, env) to pass to ``subprocess.Popen(argv, shell=False, cwd=cwd, env=env)``. - A string command runs through ``/bin/sh -c`` (the Windows sandbox: through - ``%ComSpec% /c``, as ``Popen(command, shell=True)`` does there). Raises SandboxError - when this sandbox refuses commands (kind none): callers must check ``refuses`` first.""" + A string command runs through a shell: the sandbox's own when it brings one (the Windows + sandbox: the launcher's ``--shell``, which runs ``%ComSpec% /c`` as + ``Popen(command, shell=True)`` does there; ``shell`` is not used), else ``shell`` (an + argv prefix ending in ``-c``), by default :func:`posix_shell` (pipefail when the host's + shells have it). An argv list runs as given, never through a shell (the Windows sandbox + hands it to the launcher after ``--``). Raises SandboxError when this sandbox refuses + commands (kind none): callers must check ``refuses`` first.""" if self.refuses: raise SandboxError(self.refusal()) if isinstance(command, str): - argv = [*self._shell, command] + if self._shell is not None: + argv = [*self._shell, command] + else: + argv = [*(shell or posix_shell()[0]), command] else: argv = [str(a) for a in command] if not argv: @@ -1130,6 +1222,7 @@ def refusal_result(sandbox: Sandbox, **fields: Any) -> Dict[str, Any]: "macos_profile", "normalize_spec", "path_readable", + "posix_shell", "private_tmpdir", "refusal_result", "sandbox_for_tool_call", diff --git a/abstractcore/tools/shell_session.py b/abstractcore/tools/shell_session.py index 558226a4..95bed1b1 100644 --- a/abstractcore/tools/shell_session.py +++ b/abstractcore/tools/shell_session.py @@ -11,9 +11,16 @@ REPL, `read`), `set -x`, or an unterminated quote could swallow or desync the sentinel; binary output killed the reader thread. The PTY design fixes all of these: -- The command and its sentinel are written on ONE line (`; printf … "$?"`). The shell reads and - parses the whole line before executing, so a stdin-consuming command inside `` cannot eat the - sentinel (verified: `cat`, `set -x`, binary blobs all keep the boundary intact). +- The command is written as a `{ … }` group and its status line (`printf … "$?"`, which prints + the sentinel) on the line after it, so the status line WAITS IN THE TERMINAL'S INPUT QUEUE while + the command runs. That is what lets a syntax error, or a shell the command `exec`s, still report + a status. Its cost: the first thing the command reads from the terminal is that status line. A + prompt (`read -p`, a `[Y/n]` question, Python's input()) takes it as its answer and carries on + with it, a REPL or a bare `cat` reads it as its first input, and the call then waits out its + timeout because no status line is left to print. Only a command whose input comes from + elsewhere (`echo y | cmd`, `cmd <<< y`, `cmd str: + # The sentinel printf prepends a newline; drop the single trailing newline it added. + return text[:-1] if text.endswith("\n") else text + def _pick_shell() -> Optional[str]: for candidate in ("bash", "sh"): @@ -77,16 +110,44 @@ def _shell_argv(shell_path: str) -> list[str]: # Non-login, non-rc shell to avoid profile banners / user rc noise. `sh` ignores these flags # it doesn't know only if they exist; dash accepts neither, so only add them for bash. if os.path.basename(shell_path).startswith("bash"): - return [shell_path, "--norc", "--noprofile"] + # `+H`: no history expansion, so `!` in "Hello, World!" or "#!/bin/sh" is plain text + # (an interactive bash turns it on, and an unmatched event failed the command silently). + return [shell_path, "--norc", "--noprofile", "+H"] return [shell_path] +def _quiet_terminal(fd: int) -> None: + """Clear ECHO (our written command bytes are not echoed back) and ONLCR (newlines are not + turned into \\r\\n) on the terminal ``fd``.""" + import termios + + try: + attrs = termios.tcgetattr(fd) + attrs[3] = attrs[3] & ~termios.ECHO # lflag + attrs[1] = attrs[1] & ~termios.ONLCR # oflag + termios.tcsetattr(fd, termios.TCSANOW, attrs) + except Exception: + pass + + @dataclass class ShellCommandResult: stdout: str exit_code: Optional[int] timed_out: bool = False truncated: bool = False + # Whether the session shell runs pipelines with pipefail (a failing stage fails the + # pipeline). None = not a command result (startup / read_output), or unknown. + pipefail: Optional[bool] = None + # The command ended the session shell itself (`exit`, `set -e` then a failure, a sourced + # script that exits); `exit_code` is then the shell's own exit status (None if unknown). + session_ended: bool = False + # The status line arrived but carried no readable exit code: never a success. + exit_code_unreadable: bool = False + # With `session_ended`: the shell ended while the previous, timed-out command was being + # interrupted (by that interrupt, by itself, or closed from another thread: not told apart), + # so THIS command was never run. + not_run: bool = False @dataclass @@ -107,10 +168,15 @@ class ShellSession: # None = no workspace policy (library use). Fixed at start: a `cd` cannot leave it. sandbox: Any = field(default=None, repr=False) sandbox_key: str = "" + # Measured in THIS session at start (a failing first stage must decide the status) and + # re-asserted after every command. None = unknown (the measurement did not finish). + pipefail: Optional[bool] = None + _exit_status: Optional[int] = field(default=None, repr=False) # set once the shell ended + _reap_lock: threading.Lock = field(default_factory=threading.Lock, repr=False) + _pty_closed: threading.Event = field(default_factory=threading.Event, repr=False) def start(self, *, env: Optional[Dict[str, str]] = None) -> None: import pty - import termios argv = _shell_argv(self.shell_path) sandbox = self.sandbox @@ -132,17 +198,12 @@ def start(self, *, env: Optional[Dict[str, str]] = None) -> None: pid, master_fd = pty.fork() if pid == 0: # child - # Disable ECHO (so our written command bytes aren't echoed back) and ONLCR (so newlines - # are not translated to \r\n in the output stream) BEFORE the shell starts: set from the - # parent, this raced the shell's startup, and a readline that read the terminal first - # kept echoing every command (the sentinel line included) for the whole session. - try: - attrs = termios.tcgetattr(0) - attrs[3] = attrs[3] & ~termios.ECHO # lflag - attrs[1] = attrs[1] & ~termios.ONLCR # oflag - termios.tcsetattr(0, termios.TCSANOW, attrs) - except Exception: - pass + # ECHO (so our written command bytes aren't echoed back) and ONLCR (so newlines are not + # translated to \r\n in the output stream) are cleared HERE, before exec, so the shell + # can never start its line editor with echo still on: set from the parent, this raced + # the shell's startup, and a readline that read the terminal first kept echoing every + # command (the sentinel line included) for the whole session. + _quiet_terminal(0) try: if self.cwd: os.chdir(self.cwd) @@ -159,6 +220,10 @@ def start(self, *, env: Optional[Dict[str, str]] = None) -> None: self._master_fd = master_fd def _drain() -> None: + # Line endings are normalised HERE, once, so every length the readers compute (the + # omitted count of a long output) is on the text the caller sees. A `\r\n` split + # across two reads is still one newline. + pending_cr = False while True: try: data = os.read(master_fd, _READ_CHUNK_BYTES) @@ -166,7 +231,12 @@ def _drain() -> None: break # EIO on child exit if not data: break - self._chunks.put(data.decode("utf-8", errors="replace")) + text = data.decode("utf-8", errors="replace") + if pending_cr and text.startswith("\n"): + text = text[1:] + pending_cr = text.endswith("\r") + self._chunks.put(text.replace("\r\n", "\n").replace("\r", "\n")) + self._pty_closed.set() self._chunks.put(_EOF) self._reader = threading.Thread(target=_drain, daemon=True) @@ -180,60 +250,105 @@ def _drain() -> None: # on close would ORPHAN those children. With job control off, background jobs stay in the # shell's process group and close()'s killpg reaps the whole tree. Job listing (`jobs`) and # `&` still work. - self._run_raw("set +m", timeout_s=_STARTUP_DRAIN_TIMEOUT_S) + # No completion either: a literal TAB in a command (a Makefile written by a heredoc) was + # eaten by readline's completion. `bind` is bash's; other shells ignore the line. + self._run_raw("set +m; bind 'set disable-completion on' 2>/dev/null || :", timeout_s=_STARTUP_DRAIN_TIMEOUT_S) + # Pipelines fail when any stage fails, as in execute_command (2026-11-17: a failing + # `cargo build | grep | head` reported exit 0). Tried in a subshell first so a shell + # without the option never errors in the session itself, then measured here: the + # answer is what this session's own shell does, not an assumption about its name. + self._run_raw("(set -o pipefail) 2>/dev/null && set -o pipefail", timeout_s=_STARTUP_DRAIN_TIMEOUT_S) + probe = self._run_raw("false | true", timeout_s=_STARTUP_DRAIN_TIMEOUT_S) + self.pipefail = {1: True, 0: False}.get(probe.exit_code) if not probe.timed_out else None def is_alive(self) -> bool: - if self._pid is None or self._closed: + if self._pty_closed.is_set() and self._pid is not None and not self._closed: + # The shell is gone (its terminal closed): kill the group while the exited shell + # still holds the pid, then reap it, in that order (`_reap`). + self._reap() return False - try: - done, _ = os.waitpid(self._pid, os.WNOHANG) - # waitpid returns (0, 0) while alive; (pid, status) once it exited. - return done == 0 - except ChildProcessError: + with self._reap_lock: + pid = self._pid + if pid is None or self._closed: + return False + try: + done, status = os.waitpid(pid, os.WNOHANG) + except ChildProcessError: + self._pid = None + return False + except Exception: + return True + if done == 0: + return True # waitpid returns (0, 0) while alive + # It exited while something (a background job) still holds its terminal, and THIS + # call reaped it: keep its status for the command that ended it (a concurrent run() + # reports it), end its group at once (that job keeps the group id in use, so it cannot + # name another process), and forget the pid so close() never signals a reused one. + self._exit_status = os.waitstatus_to_exitcode(status) + self._kill_group(pid) + self._pid = None return False + + @staticmethod + def _kill_group(pid: int) -> None: + try: + os.killpg(pid, signal.SIGKILL) # pty.fork made the shell its group's leader except Exception: - return True + pass - def _read_until_sentinel(self, sentinel: str, *, deadline: float) -> tuple[str, Optional[int], bool]: - """Accumulate output until `sentinel:\\n` appears. Returns (output, exit_code, timed_out). + def _read_until_sentinel(self, sentinel: str, *, deadline: float) -> "_Read": + """Accumulate output until `sentinel:[:]\\n` appears. + + Returns a `_Read`: `tail` is None when `out` is the whole output, else the last chars + kept once the head stopped growing (also on a timeout or when the shell ended, so the + LATEST output is never lost); `total` is the number of output chars (the sentinel's own + newline excluded). Bounded in BOTH cpu and memory (adversarial-review hardening): - Incremental marker search (a search offset), so a large output is scanned once β€” O(n), not O(nΒ²) which turned a finished big-output command into a FALSE timeout. - The accumulated buffer is capped: once output exceeds a head cap we stop growing it and - keep only a small rolling tail for marker detection, so multi-hundred-MB output cannot - blow up the reader's heap. `_run_raw` applies the final `_MAX_OUTPUT_CHARS` preview cap. + keep only a rolling tail (marker detection + the failure preview's tail), so + multi-hundred-MB output cannot blow up the reader's heap. `_run_raw` applies the final + `_MAX_OUTPUT_CHARS` preview cap. """ marker = sentinel + ":" head_cap = _MAX_OUTPUT_CHARS + 4096 - window = max(4096, 4 * len(marker)) + window = max(4096, 4 * len(marker)) + _FAILURE_TAIL_CHARS head = "" # bounded output capture (<= head_cap) head_search_from = 0 # incremental find offset into `head` tail = "" # rolling last `window` chars once we stop growing head + received = 0 # chars received in total truncated = False - def _finish(out: str, after: str) -> tuple[str, Optional[int], bool]: - code_str = after.split("\n", 1)[0].strip() + def _parse(after: str) -> Tuple[Optional[int], Optional[bool]]: + fields = after.split("\n", 1)[0].strip().split(":") try: - code: Optional[int] = int(code_str) + code: Optional[int] = int(fields[0]) except ValueError: code = None - # The sentinel printf prepends a newline; drop the single trailing newline it added. - if out.endswith("\n"): - out = out[:-1] - return self._normalize(out), code, False + reasserted = None if len(fields) < 2 else fields[1] == "1" + return code, reasserted + + def _unfinished(*, timed_out: bool, eof: bool) -> "_Read": + # No sentinel: a timeout or the shell ended. Keep the latest output too. + if not truncated: + out = self._normalize(head) + return _Read(out, None, timed_out, None, len(out), eof, None) + return _Read(self._normalize(head), None, timed_out, self._normalize(tail), received, eof, None) while True: remaining = deadline - time.monotonic() if remaining <= 0: self._degraded = True - return self._normalize(head), None, True + return _unfinished(timed_out=True, eof=False) try: chunk = self._chunks.get(timeout=min(remaining, 0.5)) except queue.Empty: continue if chunk is _EOF: - return self._normalize(head), None, False + return _unfinished(timed_out=False, eof=True) + received += len(chunk) if not truncated: head += chunk @@ -244,7 +359,9 @@ def _finish(out: str, after: str) -> tuple[str, Optional[int], bool]: # Exit-code newline not fully arrived; wait, but don't rescan from 0. head_search_from = idx continue - return _finish(head[:idx], after) + out = self._normalize(_strip_sentinel_newline(head[:idx])) + code, reasserted = _parse(after) + return _Read(out, code, False, None, len(out), False, reasserted) head_search_from = len(head) if len(head) > head_cap: # Switch to bounded mode: freeze the captured head, keep only a rolling tail. @@ -258,13 +375,12 @@ def _finish(out: str, after: str) -> tuple[str, Optional[int], bool]: if "\n" not in after: continue # Middle was dropped; return the captured head (β€Ή_run_rawβ€Ί adds the truncation - # note since head_cap > _MAX_OUTPUT_CHARS) and the exit code from the tail. - code_str = after.split("\n", 1)[0].strip() - try: - code = int(code_str) - except ValueError: - code = None - return self._normalize(head), code, False + # note since head_cap > _MAX_OUTPUT_CHARS), the kept tail and the exit code. + before = tail[:idx] + kept = _strip_sentinel_newline(before) + total = received - (len(tail) - idx) - (len(before) - len(kept)) + code, reasserted = _parse(after) + return _Read(self._normalize(head), code, False, self._normalize(kept), total, False, reasserted) @staticmethod def _normalize(text: str) -> str: @@ -276,24 +392,90 @@ def _write(self, data: str) -> None: def _run_raw(self, command: str, *, timeout_s: float) -> ShellCommandResult: sentinel = f"__ABSTRACT_SENTINEL_{uuid.uuid4().hex}__" - printf = f"printf '\\n%s:%s\\n' '{sentinel}' \"$?\"\n" - # NEWLINE sentinel: the printf runs as its own statement on the line AFTER the command, so - # multi-line commands, heredocs (`cat <\n\n}` and the status line after it is a plain + # `printf … "$?"`. The group is parsed as a whole before it runs, so: + # - a command line left open (a trailing `&&`, `||`, `|`, `f()`, an unclosed `if`/quote) + # is a syntax error at the `}` and fails at once with its own status, never the + # previous call's; the blank line ends a trailing `\`, which keeps its status; + # - nothing the command defines (`exit() { :; }`, `alias exit=true`) can shadow the + # status line, which uses no shell variable (a `readonly` cannot refuse it); + # - a shell the command `exec`s reads the status line too, and reports. + # Two costs. The status line waits in the terminal's input queue while the command runs, + # so the first read the command makes from the terminal gets it: a prompt (`read -p`, + # Python's input()) takes it as its ANSWER and carries on with it, a REPL reads it as its + # first input, and the call then waits out its timeout (no status line is left to print). + # The status line cannot be held back until the group has returned (it IS the signal + # that it returned). On the command's own logical line (the group inside an `eval '…'` + # followed by the printf, tried 2026-11-29) a shell the command `exec`s never prints it + # (the call waits out its timeout) and `set -x` traces the whole envelope; with the + # printf outside the `eval`, `set -e` also ends the session on a harmless + # `false && true`. So callers are told instead: give a prompt its answer in the command + # (`echo y | cmd`, `cmd /dev/null && echo 1 || echo 0)\"; " + "{ set -o pipefail || :; } >/dev/null 2>&1\n" + ) + else: + printf = f"printf '\\n%s:%s\\n' '{sentinel}' \"$?\"\n" + line = printf if not command else f"{{ :\n{command}\n\n}}\n{printf}" self._write(line) deadline = time.monotonic() + max(1.0, float(timeout_s)) - out, code, timed_out = self._read_until_sentinel(sentinel, deadline=deadline) + r = self._read_until_sentinel(sentinel, deadline=deadline) + out, code = r.out, r.code + if r.reasserted is False: + self.pipefail = False + if r.eof: + code = self._reap() truncated = False - if len(out) > _MAX_OUTPUT_CHARS: + unfinished = r.timed_out or r.eof + if (unfinished or code not in (None, 0)) and (r.tail is not None or len(out) > _MAX_OUTPUT_CHARS): + # A failing, timed-out or ending command says why at the END: keep its head AND its + # tail (the same split as execute_command). `tail` is what the reader kept once it + # stopped growing `out`. + if r.tail is None: + out, truncated = head_and_tail(out, limit=_MAX_OUTPUT_CHARS) + else: + head_part = out[: _MAX_OUTPUT_CHARS // 4] + tail_part = r.tail[-_FAILURE_TAIL_CHARS:] + out = join_head_and_tail(head_part, tail_part, max(0, r.total - len(head_part) - len(tail_part))) + truncated = True + elif len(out) > _MAX_OUTPUT_CHARS: #[WARNING:TRUNCATION] bounded session-command preview for the model out = out[:_MAX_OUTPUT_CHARS].rstrip() + "\n… (truncated; full output exceeded the preview bound)" truncated = True - return ShellCommandResult(stdout=out, exit_code=code, timed_out=timed_out, truncated=truncated) + return ShellCommandResult( + stdout=out, + exit_code=code, + timed_out=r.timed_out, + truncated=truncated, + session_ended=r.eof, + exit_code_unreadable=code is None and not unfinished, + ) + + def _reap(self) -> Optional[int]: + """The ended shell's exit status. Its process group is killed while the exited shell + (a zombie) still holds the pid, then it is reaped and the pid forgotten, so close() can + never signal a process that reuses it. A concurrent is_alive() that reaped first left + the status in `_exit_status`.""" + with self._reap_lock: + pid = self._pid + if pid is None: + return self._exit_status + self._kill_group(pid) + try: + _, status = os.waitpid(pid, 0) + self._exit_status = os.waitstatus_to_exitcode(status) + except ChildProcessError: + pass + self._pid = None + return self._exit_status def run(self, command: str, *, timeout_s: float = _DEFAULT_TIMEOUT_S) -> ShellCommandResult: """Run one command in the persistent session; returns its output + exit code. @@ -313,7 +495,14 @@ def run(self, command: str, *, timeout_s: float = _DEFAULT_TIMEOUT_S) -> ShellCo # window bled into the next command. A process that outlives the interrupt gets more # (see _resync); a session that never syncs is closed, never reused. if self._degraded: - if not self._resync(): + resynced = self._resync() + if resynced == _ENDED: + # The shell ended during the interrupt: the interrupt ended it (the timed-out + # command had `exec`ed over it, or an INT trap exits), it exited by itself, or + # another thread closed the session. Nothing kept running: it is an ended + # session, with the shell's status when known, and this command was not run. + return ShellCommandResult(stdout="", exit_code=self._reap(), session_ended=True, not_run=True) + if resynced != _SYNCED: # Output that no sync marker closed may still belong to the old command: # the session is not reused (closed, like a dead one; open() replaces it). self.close() @@ -323,45 +512,66 @@ def run(self, command: str, *, timeout_s: float = _DEFAULT_TIMEOUT_S) -> ShellCo f"{_RESYNC_ATTEMPTS} interrupts); the session was closed, start a new one" ) self._degraded = False - return self._run_raw(cmd, timeout_s=timeout_s) + result = self._run_raw(cmd, timeout_s=timeout_s) + result.pipefail = self.pipefail + return result - def _resync(self) -> bool: + def _resync(self) -> str: """Interrupt the timed-out command, then discard output up to a FRESH sync marker. - The shell prints a marker only once the foreground command has ended, and runs queued - lines in order, so everything before the latest marker is the old command's (an earlier - attempt's marker included). A command that outlives an interrupt (a trapped SIGINT, or + The command may still be running, may have ended on its own since the timeout (the + shell is then idle at its prompt), or may be waiting in a `read`: all three end with + the marker and the session kept. The shell prints a marker only once the foreground + command has ended, and runs queued lines in order, so everything before the latest + marker is the old command's (an earlier attempt's marker included). A command that outlives an interrupt (a trapped SIGINT, or bash continuing a loop whose child exited as the signal landed) gets another interrupt - and a new marker. Returns False when no attempt's marker arrives. + and a new marker. Returns `_SYNCED` once a marker arrived, `_ENDED` when the shell ended + instead (its output stream closed), `_STUCK` when no attempt's marker arrives. """ + # The Ctrl-C discarded the pending status line, and with it the pipefail re-assert. + reassert = "{ set -o pipefail || :; } >/dev/null 2>&1; " if self.pipefail else "" for _attempt in range(_RESYNC_ATTEMPTS): sync = f"__ABSTRACT_SYNC_{uuid.uuid4().hex}__" try: self._write("\x03") # ETX -> SIGINT to the foreground process group - self._write(f"printf '\\n%s\\n' '{sync}'\n") + # A no-op line goes first. A reader that was waiting on the terminal when the + # Ctrl-C landed (the shell itself, idle because the command had ended on its + # own, or its `read`) can be handed what follows the Ctrl-C BEFORE it handles the + # interrupt, and then drops it with the line it was reading: on Linux bash lost + # the sync line's first byte (`rintf: command not found`) and dash the whole + # line, on every attempt, so an idle session was closed as stuck. What such a + # reader drops is one read: a byte, or in dash a line. The `:` line is that + # read (100/100 on bash, bash --noediting and dash; without it 0 to 11). It is + # `:` and not an empty line, which a prompt that survives the interrupt would + # take as "the default answer". + self._write(f":\n{reassert}printf '\\n%s\\n' '{sync}'\n") except Exception: - return False + # The terminal took no input: the shell is gone once its output stream has closed. + return _ENDED if self._pty_closed.wait(_RESYNC_ATTEMPT_TIMEOUT_S) else _STUCK # Matched with its newline: the marker as printed, never as typed (quoted). - if self._discard_until(sync + "\n", deadline=time.monotonic() + _RESYNC_ATTEMPT_TIMEOUT_S): - return True - return False - - def _discard_until(self, marker: str, *, deadline: float) -> bool: + outcome = self._discard_until(sync + "\n", deadline=time.monotonic() + _RESYNC_ATTEMPT_TIMEOUT_S) + if outcome != _STUCK: + return outcome + return _STUCK + + def _discard_until(self, marker: str, *, deadline: float) -> str: + """Discard output up to `marker`: `_SYNCED` once it was read, `_ENDED` when the stream + ended first (the shell is gone, so no later attempt can help), `_STUCK` at the deadline.""" seen = "" while True: remaining = deadline - time.monotonic() if remaining <= 0: - return False + return _STUCK try: chunk = self._chunks.get(timeout=min(remaining, 0.5)) except queue.Empty: continue if chunk is _EOF: - return False + return _ENDED # Only a tail long enough to hold a marker split across chunks is kept. seen = (seen + chunk)[-(len(marker) + 4096):] if marker in seen: - return True + return _SYNCED def write_stdin(self, data: str) -> None: """Feed raw input to the session (for interactive prompts / REPLs).""" @@ -385,6 +595,7 @@ def read_output(self, *, timeout_s: float = 2.0, idle_s: float = 0.5, max_chars: idle = max(0.05, float(idle_s)) out = "" got_any = False + ended = False while True: now = time.monotonic() if now >= deadline: @@ -398,6 +609,7 @@ def read_output(self, *, timeout_s: float = 2.0, idle_s: float = 0.5, max_chars: break continue if chunk is _EOF: + ended = True break out += chunk got_any = True @@ -409,14 +621,19 @@ def read_output(self, *, timeout_s: float = 2.0, idle_s: float = 0.5, max_chars: #[WARNING:TRUNCATION] bounded interactive-read preview for the model out = out[:max_chars].rstrip() + "\n… (truncated; full output exceeded the preview bound)" truncated = True + if ended: + # The input ended the shell (`exit 3` typed into it): its status, reaped. + return ShellCommandResult(stdout=out, exit_code=self._reap(), truncated=truncated, session_ended=True) return ShellCommandResult(stdout=out, exit_code=None, timed_out=False, truncated=truncated) def close(self) -> None: self._closed = True - pid = self._pid fd = self._master_fd # Kill the whole process group (the PTY session leader), reaping foreground + background # children so nothing is orphaned; then reap the shell to avoid a zombie. + with self._reap_lock: + pid = self._pid + self._pid = None if pid is not None: try: os.killpg(os.getpgid(pid), signal.SIGKILL) diff --git a/abstractcore/tools/shell_tools.py b/abstractcore/tools/shell_tools.py index 139816c1..bb945281 100644 --- a/abstractcore/tools/shell_tools.py +++ b/abstractcore/tools/shell_tools.py @@ -2,7 +2,8 @@ These expose the persistent PTY shell engine (`shell_session.py`) as tools a model can call: `shell_exec` runs commands in a session whose working directory and environment persist across -calls; `shell_write_stdin` feeds input to an interactive foreground process (REPL, prompt); +calls; `shell_write_stdin` feeds input to an interactive foreground process (a REPL, a later +prompt of a running command; its FIRST prompt has already read `shell_exec`'s status line); `shell_close` ends a session. Safety posture (deliberate, per backlog 0220): @@ -28,8 +29,15 @@ from __future__ import annotations -from typing import Optional +from typing import Any, Dict, Optional +from .command_verdict import ( + NO_PIPEFAIL_NOTE, + UNKNOWN_PIPEFAIL_NOTE, + UNREADABLE_EXIT_CODE_SENTENCE, + command_failure_sentence, + session_ended_sentence, +) from .core import tool from .sandbox import KIND_UNSANDBOXED, sandbox_for_tool_call from .shell_session import ( @@ -67,26 +75,60 @@ def _render_result(result: ShellCommandResult, *, prefix_lines: Optional[list] = parts: list[str] = list(prefix_lines or []) if result.timed_out: parts.append( - "[timed out β€” the foreground process may still be running. Feed it input with " - "shell_write_stdin, retry later, or shell_close the session to kill it.]" + "[timed out β€” the foreground process may still be running. If it is still waiting " + "for input, feed it with shell_write_stdin; otherwise retry later, or shell_close the " + "session to kill it.]" ) if result.exit_code is not None: parts.append(f"exit_code: {result.exit_code}") + # Same verdict wording as execute_command (exit code only, output never scanned). + if result.session_ended: + pass + elif result.pipefail is False: + parts.append(NO_PIPEFAIL_NOTE) + elif result.pipefail is None: + parts.append(UNKNOWN_PIPEFAIL_NOTE) out = result.stdout if result.stdout else "(no output)" parts.append(out) + failure = _failure(result) + if failure and not result.timed_out: + parts.append(f"❌ {failure}") return "\n".join(parts) +def _failure(result: ShellCommandResult, *, timeout_s: Optional[float] = None) -> Optional[str]: + """The failure sentence of a command result, or None when it succeeded.""" + if result.session_ended: + return session_ended_sentence(result.exit_code, not_run=result.not_run) + if result.timed_out: + within = f" after {timeout_s:g}s" if timeout_s else "" + return ( + f"Command timed out{within}; the session survives (feed it with shell_write_stdin if it is " + "still waiting for input, or shell_close it)" + ) + if result.exit_code_unreadable: + return UNREADABLE_EXIT_CODE_SENTENCE + if result.exit_code not in (None, 0): + return command_failure_sentence(int(result.exit_code)) + return None + + +def _refused(command: str, message: str, rendered: Optional[str] = None) -> Dict[str, Any]: + return {"success": False, "error": message, "command": command, "rendered": rendered or f"Error: {message}"} + + @tool( + # The prompt warning is what really happens (shell_session._run_raw): the status line waits + # in the terminal's input queue, so a prompt reads it as its answer and carries on. description=( - "Run a command in a PERSISTENT shell session (cwd/env/venv persist across calls). " - "Sandboxed to this run's workspaces when the host sets a workspace policy; NOT durable " - "(never survives a host restart)." + "Run a command in a PERSISTENT shell session (cwd/env/venv persist; sandboxed under a " + "workspace policy; NOT durable). A prompt reads the tool's status line as its answer: " + "pipe one in (echo y | cmd)." ), when_to_use=( - "Multi-step shell workflows where state must persist: activate a venv then run tools in it, " - "cd and work there, start a background process (`&`) and inspect it later. A 'new shell " - "session' notice in output means prior state is gone." + "Stateful shell work (venv, cd, background & jobs); a 'new shell session' notice means " + "prior state is gone. Never pipe into head. Group grep tests: cmd | { grep pat || [ $? -eq 1 ]; }, " + "cmd | { grep pat >/dev/null && echo y || echo n; }" ), # Side-effect tag for consumers (abstractagent repeat-guard reads # ToolDefinition.tags); mirrors tools/inventory.py β€” test-pinned. @@ -105,33 +147,45 @@ def shell_exec( timeout: float = 120, _registry_namespace: str = "", _sandbox: Optional[dict] = None, -) -> str: +) -> Dict[str, Any]: """Run `command` in the persistent session `session_id`, creating it if needed. `working_directory` sets the INITIAL cwd when the session is first created (ignored on an existing session β€” use `cd` there). `timeout` bounds this call in seconds; on timeout the - session survives and resyncs on the next call (one that cannot resync is closed, and that - call says so). + session survives and resyncs on the next call, which interrupts what is still in the + foreground and runs its command in the same session whether the timed-out command is still + running, has ended on its own or is waiting at a prompt (one that cannot resync is closed, and that + call says so; one whose shell ended while it was being interrupted is reported as ended, with + the shell's exit code or signal and `not_run: true`: that call's command was not run). + + Do not start a command that prompts (`read -p`, a `[Y/n]` confirmation, an installer's + question) bare: the tool's status line is already waiting in the terminal's input queue, so + the prompt reads it as its answer and carries on with it, and the call then waits out its + timeout. Give the answer in the command (`echo y | cmd`, `cmd <<< y`, the command's own + `--yes` flag) or take its input away (`cmd str: +) -> Dict[str, Any]: """Write `input` (newline-terminated) to the session's foreground process and read output. + The process must still be waiting for input (a REPL, a later prompt of a running command). + A command's first prompt is not: it read `shell_exec`'s status line as its answer and went + on, so once that call has timed out nothing is waiting and the input is typed into the shell + itself, which runs it as a command (`y: command not found`). + Args: input: Text written to the session's foreground process, newline-terminated (one line per call). session_id: Session whose foreground process receives the input (default: "main"). @@ -182,16 +265,29 @@ def shell_write_stdin( key = namespaced_session_id(_registry_namespace, sid) session = get_shell_session_registry().get(key) if session is None or not session.is_alive(): - return ( - f"Error: no active shell session '{sid}'. Start one with shell_exec first " + message = ( + f"no active shell session '{sid}'. Start one with shell_exec first " "(sessions do not survive host restarts)." ) + return {"success": False, "error": message, "session_id": sid, "rendered": f"Error: {message}"} try: session.write_stdin(str(input if input is not None else "")) result = session.read_output(timeout_s=_coerce_float(read_timeout, 5.0, cap=_MAX_TIMEOUT_S)) except Exception as e: - return f"Error: shell session failed: {e}" - return _render_result(result) + message = f"shell session failed: {e}" + return {"success": False, "error": message, "session_id": sid, "rendered": f"Error: {message}"} + # An interactive read has no exit code; only input that ended the shell is a failure. + failure = _failure(result) + return { + "success": failure is None, + "error": failure, + "session_id": sid, + "return_code": result.exit_code, + "exit_code": result.exit_code, + "session_ended": bool(result.session_ended), + "output_truncated": bool(result.truncated), + "rendered": _render_result(result), + } @tool( diff --git a/changelog.d/execute-command-pipefail.md b/changelog.d/execute-command-pipefail.md new file mode 100644 index 00000000..d6d0981a --- /dev/null +++ b/changelog.d/execute-command-pipefail.md @@ -0,0 +1,61 @@ +### Fixed + +- **On Linux, a shell session is kept after a timed-out command that has ended on its own** + (`tools/shell_session.py`). The `shell_exec` call that follows a timeout interrupts the session and + waits for a marker line. When the timed-out command was no longer running (it finished late, or its + prompt had read the tool's status line and carried on) or was waiting in the shell's `read`, the reader + on the terminal was handed the start of the marker line before it handled the interrupt and dropped it: + bash ran `rintf …`, dash lost the whole line, on each of the three attempts. Since 2.40.0 that call + failed after 15 seconds with "could not be resynchronised … (its foreground process kept running through + 3 interrupts)" although nothing was running, and the session was closed with its working directory and + environment. A no-op line now precedes the marker line, so the call runs in the same session. macOS was + not affected. +- **A failing command in a pipeline fails `execute_command` and `shell_exec`** (`tools/common_tools.py`, + `tools/command_verdict.py`, `tools/sandbox.py`, `tools/shell_session.py`, `tools/shell_tools.py`). Commands + ran in `/bin/sh` without pipefail, so a pipeline reported its last stage's status: `cargo build 2>&1 | + grep -E '^error' | head -60` failed to build and the tool said "Return code: 0" and "Command completed + successfully". + - `execute_command`: POSIX string commands, sandboxed or not, run in `/bin/sh -o pipefail -c` when that + shell supports it (macOS, where `/bin/sh` is bash; Ubuntu's dash 0.5.12), else in + `bash --posix -o pipefail -c`, else in plain `/bin/sh -c`. The choice is probed once per process; a + probe that gave no answer is not remembered. Neither shell reads `$BASH_ENV`. The result's new + `pipefail` field says whether pipefail was on, and the render says so when it was not. A non-zero + exit reads "❌ Command failed (exit code N)" with `success: false`, the full stdout/stderr, "(no + output)" when there was none and the signal name when one killed the shell; a long failing output + keeps its head and its tail in the preview (a successful one keeps its head, as before). Exit 141 + says it is a process killed by SIGPIPE, usually cut off by a stage such as `head` that stopped reading. + On Windows the command still runs in `cmd.exe` (the Windows sandbox runs a string command through its + own launcher as before), which has no pipefail: `pipefail` is false, every finished command's result says that a pipeline + reports its last command's exit code, and the description, guidance and examples the model reads there + are the `cmd.exe` ones (no pipefail promise, no POSIX grouping syntax). + - `shell_exec` now returns a dict instead of plain text: `success`, `error` (a short sentence on failure), + `command`, `session_id`, `return_code`/`exit_code`, `pipefail`, `timed_out`, `session_ended`, + `not_run`, `output_truncated`, `rendered` (the previous text) and, under a sandbox, `sandbox`. `success` is false on a + non-zero exit, an exit code that could not be read, a timeout (the wait is `timeout` seconds, at most 600 + and at least 1; 0, a negative or a non-numeric value means 120), or a command that ended the session shell (`exit 3`, `set -e` then a failure, a sourced script that exits, + `exit 0` too, since the session's state is lost): "The shell session ended during this command (exit code + N)", with the signal named when one killed it. Refusals (an empty command, no sandbox, a session that could + not start, a session closed because it could not be resynchronised after a timed-out command) are `{success: false, error, command, rendered}`. When the shell ends while the interrupt sent before the next command is under way (the timed-out command was `exec sleep 100`, an INT trap exits, the shell exits by itself, or the session is closed from elsewhere), that call reports an ended session with the shell's exit code or signal when known, `not_run: true`, and an error saying its command was not run. Each command runs in a + `{ … }` group read as a whole, so a command line left open (a trailing `&&`, `||` or `|`, an unclosed `if` + or quote) fails at once with a syntax error instead of reporting the previous call's status, a trailing + `\` keeps its status, and nothing the command + defines (`exit() { :; }`, an alias) can change the reported status; an alias defined in a call applies + from the next call. The status line waits in the terminal's input queue while the command runs, so a + command that prompts (`read -p`, a `[Y/n]` confirmation) reads it as its answer and carries on with it, + and the call then waits out its timeout: the `shell_exec` description tells the model not to start a + prompting command bare and to give the answer in the command (`echo y | cmd`); `shell_write_stdin` + and the timeout message say that only a process still waiting for input (a REPL, a later prompt of + the same command) can be fed. History expansion is off (`!` is literal), completion is off (a TAB reaches the + command), and the terminal never echoes commands back. Each session turns pipefail on at + start, measures it in the session itself and turns it back on after every command and after a timeout; + a shell that refuses it (for example after `exec dash`) is then reported as having none, and an unfinished + measurement as unknown. A long failing or timed-out output keeps its head and its latest output; omitted + counts are on the normalised text. Callers that used the returned string now read `rendered`. + - `shell_write_stdin` also returns a dict: `success`, `error`, `session_id`, `return_code`/`exit_code` + (null unless the input ended the shell), `session_ended`, `output_truncated`, `rendered`; input that ends + the shell (`exit 3`) is a failure, and a refusal (no active session, a failed write) is + `{success: false, error, session_id, rendered}`. `shell_close` still returns text. + - Both tools teach grouped grep tests on macOS and Linux, so the producer's failure still counts: + `cmd | { grep pat || [ $? -eq 1 ]; }` accepts no match (grep's own errors still fail) and + `cmd | { grep pat >/dev/null && echo yes || echo no; }` tests for a match; and that output is + already previewed, so piping into `head` is unnecessary. diff --git a/docs/tool-calling.md b/docs/tool-calling.md index 23c2d897..55f65d5a 100644 --- a/docs/tool-calling.md +++ b/docs/tool-calling.md @@ -179,6 +179,7 @@ directory_listing = list_files(".", pattern="*.py", recursive=True) - `web_search` - Search the web using DuckDuckGo. See [Web and Document Tools](web-tools.md). - `skim_websearch` - Smaller, optionally keyword-filtered search result list. See [Web and Document Tools](web-tools.md). - `execute_command` - Execute shell commands safely with security controls, inside the run's OS sandbox (see *Command sandbox* below) + - On macOS and Linux, pipelines run with pipefail (`/bin/sh -o pipefail` when that shell supports it, else `bash --posix`; the result's `pipefail` field says whether it is on), so any failing stage fails the command. On Windows the command runs in `cmd.exe`, which has no pipefail: a pipeline reports its last command's exit code, `pipefail` is false and every finished command's result says so, and the tool's description, guidance and examples are the `cmd.exe` ones (no pipefail promise, no POSIX grouping syntax). A non-zero exit returns `success: false`, "Command failed (exit code N)" and the full stdout/stderr, and a long failing output keeps its head and its tail in the preview; exit 141 is a process killed by SIGPIPE, usually cut off by a stage such as `head` or `grep -q` that stopped reading. Keep grep tests inside a group so the producer's failure still counts: `cmd | { grep pat || [ $? -eq 1 ]; }` accepts no match, `cmd | { grep pat >/dev/null && echo yes || echo no; }` tests for one. - `browser_probe` - Render a URL or local HTML file in a **headless browser** (Playwright) and verify it actually DISPLAYS β€” the blank-page class that passes `read_file` review (an agent writes an HTML/JS app, the source looks right, the page renders empty). Returns a `PASS`/`FAIL` verdict with navigation outcome, HTTP status, `readyState`, title, visible-text stats, per-check results (`require_nonblank`, `expect_selector`, `expect_text`), captured console errors + uncaught exceptions (a page can render and still be broken), and an optional screenshot path to feed `analyze_media` for a visual pass. Runs in a worker subprocess with a hard wall-clock kill (never hangs on an infinite-JS-loop page, never leaks a browser); readiness is a content signal, never `networkidle` (refused with teaching) or `sleep`. Local targets (a path or a `file://` URL) are **served from a private loopback origin, never opened as `file://`**: with a host's run scope (the `_sandbox` stamp) the origin answers only for files that scope can read, `file://` subresources and files outside the scope are refused and listed ("Local files BLOCKED"), and ES modules and `fetch()` of the page's own files work as over any http server. Local targets **block outbound network by default** (a generated page must not phone home; blocked requests are reported). Requires Playwright, which the light install does not include (`abstractcore[apple]` and `abstractcore[gpu]` do): install one of those, then `python -m playwright install --only-shell chromium` (Linux also needs `python -m playwright install --with-deps chromium`); an absent dependency returns an actionable two-step install hint, never a traceback. - `analyze_media` - Answer a question about an image. Delegated sight: the session model's own vision when available, else the configured vision fallback. Returns bounded text β€” never raw image data into your context @@ -225,8 +226,49 @@ output). Unified-diff mode handles deletion of lines whose content starts with ` `shell_close` β€” a persistent PTY-backed shell whose working directory, environment, and activated venvs survive across calls (`session_id` selects the session). Use them for multi-step workflows such as creating a venv in one call and installing into it in the -next, feeding input to a REPL or prompt, or starting a background process and inspecting -it later. +next, feeding input to a REPL or to a later prompt of a running command, or starting a +background process and inspecting it later. + +`shell_exec` returns a dict: `success`, `error` (a short sentence on failure, else null), +`command`, `session_id`, `return_code` and `exit_code` (the same value), `pipefail`, `timed_out`, +`session_ended`, `not_run`, `output_truncated`, `rendered` (the text the model reads) and, under a +sandbox, `sandbox`. `success` is false on a non-zero exit, an exit code that could not be read, a timeout, +or a command that ended the session shell (`exit 0` included, since its state is lost). The call +waits `timeout` seconds: at most 600 and at least 1; 0, a negative or a non-numeric value means 120. +After a timeout the session is kept: the next `shell_exec` interrupts whatever is still in the +foreground and runs its command in the same session (working directory and environment as they +were), whether the timed-out command is still running, has ended on its own or is waiting at a +prompt, on macOS and on Linux. A process that survives three interrupts (a REPL) gets the session +closed instead, and that call says so. +A command line left open (a trailing `&&`, `||` or `|`, an unclosed `if` or quote) fails at once +with a syntax error. `!` is literal (no +history expansion) and a TAB reaches the command as typed. An alias defined in a call applies from +the next call. A refusal (an empty command, no sandbox, a session +that could not start, a session closed because it could not be resynchronised after a timed-out +command) is `{success: false, error, command, rendered}`. When the shell ends while the interrupt +sent before the next command is under way (the timed-out command was `exec sleep 100`, an INT trap +exits, the shell exits by itself, or the session is closed from elsewhere), that call reports an +ended session instead: `session_ended` and `not_run` true, the shell's exit code or signal when +known, and an `error` saying the command was not run. `not_run` is false on every other result. + +Do not start a command that prompts with `shell_exec`. The tool's status line is already waiting in +the terminal's input queue while the command runs, so a prompt (`read -p`, a `[Y/n]` confirmation, +an installer's question) reads that line as its answer and carries on with it, and the call then +waits out its `timeout`: `read -n 1 -s -p 'Press any key to deploy' k; echo DEPLOYED` prints +`DEPLOYED`. Give the answer in the command (`echo y | cmd`, `cmd <<< y`, the command's own `--yes` +flag) or take its input away (`cmd /dev/null && echo yes || echo no; }` tests for one. - `browser_probe` - Render a URL or local HTML file in a **headless browser** (Playwright) and verify it actually DISPLAYS β€” the blank-page class that passes `read_file` review (an agent writes an HTML/JS app, the source looks right, the page renders empty). Returns a `PASS`/`FAIL` verdict with navigation outcome, HTTP status, `readyState`, title, visible-text stats, per-check results (`require_nonblank`, `expect_selector`, `expect_text`), captured console errors + uncaught exceptions (a page can render and still be broken), and an optional screenshot path to feed `analyze_media` for a visual pass. Runs in a worker subprocess with a hard wall-clock kill (never hangs on an infinite-JS-loop page, never leaks a browser); readiness is a content signal, never `networkidle` (refused with teaching) or `sleep`. Local targets (a path or a `file://` URL) are **served from a private loopback origin, never opened as `file://`**: with a host's run scope (the `_sandbox` stamp) the origin answers only for files that scope can read, `file://` subresources and files outside the scope are refused and listed ("Local files BLOCKED"), and ES modules and `fetch()` of the page's own files work as over any http server. Local targets **block outbound network by default** (a generated page must not phone home; blocked requests are reported). Requires Playwright, which the light install does not include (`abstractcore[apple]` and `abstractcore[gpu]` do): install one of those, then `python -m playwright install --only-shell chromium` (Linux also needs `python -m playwright install --with-deps chromium`); an absent dependency returns an actionable two-step install hint, never a traceback. - `analyze_media` - Answer a question about an image. Delegated sight: the session model's own vision when available, else the configured vision fallback. Returns bounded text β€” never raw image data into your context @@ -7223,8 +7224,49 @@ output). Unified-diff mode handles deletion of lines whose content starts with ` `shell_close` β€” a persistent PTY-backed shell whose working directory, environment, and activated venvs survive across calls (`session_id` selects the session). Use them for multi-step workflows such as creating a venv in one call and installing into it in the -next, feeding input to a REPL or prompt, or starting a background process and inspecting -it later. +next, feeding input to a REPL or to a later prompt of a running command, or starting a +background process and inspecting it later. + +`shell_exec` returns a dict: `success`, `error` (a short sentence on failure, else null), +`command`, `session_id`, `return_code` and `exit_code` (the same value), `pipefail`, `timed_out`, +`session_ended`, `not_run`, `output_truncated`, `rendered` (the text the model reads) and, under a +sandbox, `sandbox`. `success` is false on a non-zero exit, an exit code that could not be read, a timeout, +or a command that ended the session shell (`exit 0` included, since its state is lost). The call +waits `timeout` seconds: at most 600 and at least 1; 0, a negative or a non-numeric value means 120. +After a timeout the session is kept: the next `shell_exec` interrupts whatever is still in the +foreground and runs its command in the same session (working directory and environment as they +were), whether the timed-out command is still running, has ended on its own or is waiting at a +prompt, on macOS and on Linux. A process that survives three interrupts (a REPL) gets the session +closed instead, and that call says so. +A command line left open (a trailing `&&`, `||` or `|`, an unclosed `if` or quote) fails at once +with a syntax error. `!` is literal (no +history expansion) and a TAB reaches the command as typed. An alias defined in a call applies from +the next call. A refusal (an empty command, no sandbox, a session +that could not start, a session closed because it could not be resynchronised after a timed-out +command) is `{success: false, error, command, rendered}`. When the shell ends while the interrupt +sent before the next command is under way (the timed-out command was `exec sleep 100`, an INT trap +exits, the shell exits by itself, or the session is closed from elsewhere), that call reports an +ended session instead: `session_ended` and `not_run` true, the shell's exit code or signal when +known, and an `error` saying the command was not run. `not_run` is false on every other result. + +Do not start a command that prompts with `shell_exec`. The tool's status line is already waiting in +the terminal's input queue while the command runs, so a prompt (`read -p`, a `[Y/n]` confirmation, +an installer's question) reads that line as its answer and carries on with it, and the call then +waits out its `timeout`: `read -n 1 -s -p 'Press any key to deploy' k; echo DEPLOYED` prints +`DEPLOYED`. Give the answer in the command (`echo y | cmd`, `cmd <<< y`, the command's own `--yes` +flag) or take its input away (`cmd =0.32.4" in error["message"] and "0.31.2" in error["message"] + assert f"mlx>={mflux.MLX_VERSION_FLOOR}" in error["message"] and "0.31.2" in error["message"] def test_a_model_a_failed_default_run_left_loaded_is_listed_and_unloads(client): diff --git a/tests/tools/test_common_tools_execute_command.py b/tests/tools/test_common_tools_execute_command.py index bad0827f..eb8cb27b 100644 --- a/tests/tools/test_common_tools_execute_command.py +++ b/tests/tools/test_common_tools_execute_command.py @@ -8,6 +8,7 @@ import pytest from tests.timing import timing_budget # wall-clock budgets: reported, asserted only under ABSTRACTCORE_TIMING_STRICT=1 +from abstractcore.tools.command_verdict import NO_PIPEFAIL_NOTE from abstractcore.tools.common_tools import execute_command @@ -274,8 +275,263 @@ def test_success_render_byte_stable_without_clamp() -> None: f"πŸ“ Working directory: {out['working_directory']}", f"⏱️ Execution time: {out['duration_s']:.2f}s", "πŸ”’ Return code: 0", + *([] if out["pipefail"] else [NO_PIPEFAIL_NOTE]), # cmd.exe, or a /bin/sh without it "\nπŸ“€ STDOUT:\nstable_OUT\n", "\nβœ… Command completed successfully", ] ) assert out["rendered"] == expected + + +# --------------------------------------------------------------------------- +# Pipelines fail when any stage fails (2026-11-17: `cargo build 2>&1 | grep -E +# '^error' -A 7 | head -60` failed to build, and the tool said "Return code: 0" +# and "Command completed successfully"). The verdict comes from the exit code +# alone; stdout/stderr are kept in full and never scanned. +# --------------------------------------------------------------------------- + +posix_only = pytest.mark.skipif(os.name != "posix", reason="pipefail applies to POSIX shells") + + +@posix_only +def test_failing_first_stage_of_a_pipe_fails_the_command() -> None: + out = execute_command("sh -c 'exit 3' | cat", timeout=10) + assert out["pipefail"] is True + assert out["success"] is False + assert out["return_code"] == 3 + assert out["error"] == "Command failed (exit code 3)" + assert "❌ Command failed (exit code 3)" in out["rendered"] + + +@posix_only +def test_the_reported_cargo_shape_is_a_failure_with_its_output() -> None: + cmd = "sh -c 'echo error: x; echo noise; exit 101' 2>&1 | grep -E '^error' -A 7 | head -60" + out = execute_command(cmd, timeout=10) + assert out["success"] is False + assert out["return_code"] == 101 + assert "error: x" in out["stdout"] + rendered = out["rendered"] + assert "πŸ”’ Return code: 101" in rendered + assert "error: x" in rendered + assert rendered.endswith("❌ Command failed (exit code 101)") + assert "completed successfully" not in rendered + assert "non-zero exit code" not in rendered + + +@posix_only +def test_successful_pipeline_succeeds() -> None: + out = execute_command("printf 'a\\nb\\n' | grep b | cat", timeout=10) + assert out["success"] is True + assert out["return_code"] == 0 + assert out["error"] is None + assert out["stdout"] == "b\n" + assert out["pipefail"] is True + + +@posix_only +def test_sigpipe_exit_141_is_a_failure_that_names_the_cut_off() -> None: + out = execute_command("yes | head -n 1", timeout=10) + assert out["success"] is False + assert out["return_code"] == 141 + assert out["stdout"] == "y\n" + assert "killed by SIGPIPE" in out["error"] and "cut off before finishing" in out["error"] + assert "rerun without that stage" in out["rendered"] + + +@posix_only +def test_nonzero_exit_without_capture_still_says_failed() -> None: + out = execute_command("exit 5", timeout=10, capture_output=False) + assert out["success"] is False + assert "❌ Command failed (exit code 5)" in out["rendered"] + + +@posix_only +def test_shell_without_pipefail_is_visible(monkeypatch: pytest.MonkeyPatch) -> None: + from abstractcore.tools import sandbox as sb + + monkeypatch.setattr(sb, "_SHELL", (("/bin/sh", "-c"), False)) + out = execute_command("echo hi", timeout=10) + assert out["success"] is True + assert out["pipefail"] is False + assert "this shell has no pipefail" in out["rendered"] + + +@posix_only +def test_tool_metadata_teaches_pipefail_and_no_truncating_pipes() -> None: + td = execute_command._tool_definition + assert "pipefail" in td.description + assert "head" in td.when_to_use and "[ $? -eq 1 ]" in td.when_to_use + for ex in td.examples or []: + assert "| head" not in str(ex.get("arguments", {}).get("command", "")) + + +# --- review round 2 (2026-11-17) -------------------------------------------------------- + + +@posix_only +def test_taught_match_test_after_a_pipe_survives_a_large_producer() -> None: + # `grep -q` exits at the first match; the producer then gets SIGPIPE (141) and pipefail + # fails the pipeline, inverting `&& yes || no`. The taught `grep pat >/dev/null` reads it all. + out = execute_command("seq 1 200000 | grep -E '^5$' >/dev/null && echo yes || echo no", timeout=30) + assert out["success"] is True and out["stdout"] == "yes\n", out["rendered"] + td = execute_command._tool_definition + assert "cmd | { grep pat >/dev/null && echo y || echo n; }" in td.when_to_use + + +@posix_only +def test_taught_match_test_keeps_a_failing_producer() -> None: + # Ungrouped, `producer | grep pat >/dev/null && echo yes || echo no` answers CLEAN with rc 0 + # when the producer fails (the `||` branch swallows the pipeline's failure). + cmd = "sh -c 'echo \"error: boom\"; exit 101' 2>&1 | { grep error >/dev/null && echo HAS_ERRORS || echo CLEAN; }" + out = execute_command(cmd, timeout=10) + assert out["success"] is False and out["return_code"] == 101 + assert out["stdout"] == "HAS_ERRORS\n" + no_match = execute_command("echo a | { grep zzz >/dev/null && echo yes || echo no; }", timeout=10) + assert no_match["success"] is True and no_match["stdout"] == "no\n" + big = execute_command("seq 1 200000 | { grep -E '^5$' >/dev/null && echo yes || echo no; }", timeout=30) + assert big["success"] is True and big["stdout"] == "yes\n", big["rendered"] + + +@posix_only +def test_taught_no_match_form_keeps_the_producers_and_greps_own_failure() -> None: + failed = execute_command("sh -c 'echo a; exit 101' | { grep zzz || [ $? -eq 1 ]; }", timeout=10) + assert failed["success"] is False and failed["return_code"] == 101 + no_match = execute_command("echo a | { grep zzz || [ $? -eq 1 ]; }", timeout=10) + assert no_match["success"] is True and no_match["return_code"] == 0 + bad_pattern = execute_command("echo a | { grep -E '(' || [ $? -eq 1 ]; }", timeout=10) + assert bad_pattern["success"] is False # grep's own error (exit 2) still fails + td = execute_command._tool_definition + assert "cmd | { grep pat || [ $? -eq 1 ]; }" in td.when_to_use + assert "|| true" not in td.when_to_use + assert all("|| true" not in str(ex["arguments"]["command"]) for ex in td.examples) + + +@posix_only +def test_long_failing_output_keeps_its_tail() -> None: + cmd = "i=0; while [ $i -lt 2000 ]; do echo \"filler_line_${i}_xxxxxxxxxx\"; i=$((i+1)); done; printf 'FINAL_%s\\n' BUILD_ERROR; exit 2" + out = execute_command(cmd, timeout=30) + assert len(out["stdout"]) > 51_000 + assert out["success"] is False and out["return_code"] == 2 + assert out["stdout_truncated"] is True + rendered = out["rendered"] + assert "FINAL_BUILD_ERROR" in rendered + assert "filler_line_0_" in rendered # the head is kept too + stdout = out["stdout"] + assert f"\n... ({len(stdout) - 20000} chars omitted) ...\n{stdout[-15000:]}" in rendered + assert f"πŸ“€ STDOUT:\n{stdout[:5000]}\n... (" in rendered + assert "`stdout`" not in rendered and "field" not in rendered # the runtime may pop/offload it + assert rendered.endswith("❌ Command failed (exit code 2)") + + +@posix_only +def test_long_successful_output_still_keeps_its_head_only() -> None: + cmd = "i=0; while [ $i -lt 1700 ]; do echo \"filler_line_${i}_xxxxxxxxxx\"; i=$((i+1)); done; printf 'FINAL_%s\\n' OK_MARK" + out = execute_command(cmd, timeout=30) + assert out["success"] is True + assert "FINAL_OK_MARK" not in out["rendered"] and "(output truncated," in out["rendered"] + + +@posix_only +def test_failure_without_output_says_so() -> None: + out = execute_command("exit 9", timeout=10) + assert out["success"] is False + assert out["rendered"].endswith("\n(no output)\n\n❌ Command failed (exit code 9)") + noisy = execute_command("echo something; exit 9", timeout=10) + assert "(no output)" not in noisy["rendered"] + + +@posix_only +def test_a_signal_that_killed_the_shell_is_named() -> None: + out = execute_command("kill -KILL $$", timeout=10) + assert out["success"] is False and out["return_code"] == -9 + assert out["error"] == "Command failed (exit code -9): terminated by SIGKILL" + assert "terminated by SIGKILL" in out["rendered"] + + +@posix_only +def test_head_is_still_warned_against_tail_is_not() -> None: + w = execute_command._tool_definition.when_to_use + assert "never pipe into head" in w and "tail" not in w + + +@posix_only +def test_long_failing_stderr_keeps_its_tail() -> None: + cmd = "i=0; while [ $i -lt 600 ]; do echo \"err_line_${i}_xxxxxxxxxx\" >&2; i=$((i+1)); done; printf 'LAST_%s\\n' STDERR_ERROR >&2; exit 3" + out = execute_command(cmd, timeout=30) + assert len(out["stderr"]) > 5000 and out["stderr_truncated"] is True + assert "LAST_STDERR_ERROR" in out["rendered"] + stderr = out["stderr"] + assert f"❌ STDERR:\n{stderr[:1250]}\n... ({len(stderr) - 5000} chars omitted) ...\n{stderr[-3750:]}" in out["rendered"] + assert "err_line_0_" in out["rendered"] + + +@posix_only +def test_plain_exit_141_is_not_blamed_on_a_pipeline_stage() -> None: + out = execute_command("exit 141", timeout=10) + assert out["success"] is False and out["return_code"] == 141 + assert "later pipeline stage" not in out["error"] + assert "usually" in out["error"] + + +@posix_only +def test_the_shell_is_resolved_once_per_call(monkeypatch: pytest.MonkeyPatch) -> None: + from abstractcore.tools import sandbox as sb + + calls = [] + answers = iter([(("/bin/sh", "-c"), False), (("/bin/sh", "-o", "pipefail", "-c"), True)]) + + def flaky(): + calls.append(1) + return next(answers) + + monkeypatch.setattr(sb, "posix_shell", flaky) + out = execute_command("sh -c 'exit 3' | cat", timeout=10) + assert len(calls) == 1 + assert out["pipefail"] is False and out["return_code"] == 0 # the argv and the field agree + + +# --- review of the merge (2026-11-29): what the model is told is true on Windows too --------- + + +class _WindowsOs: + """`os` as common_tools sees it on Windows: only its name differs. The command then runs the + way it does there (`shell=True`, no pipefail prefix); on a POSIX host that shell is /bin/sh.""" + + name = "nt" + + def __getattr__(self, key): + return getattr(os, key) + + +def test_on_windows_every_result_says_a_pipeline_reports_its_last_command(monkeypatch: pytest.MonkeyPatch) -> None: + from abstractcore.tools import common_tools + + monkeypatch.setattr(common_tools, "os", _WindowsOs()) + out = execute_command("echo hi", timeout=10) + assert out["success"] is True and out["pipefail"] is False + assert NO_PIPEFAIL_NOTE in out["rendered"].splitlines() + assert "this shell has no pipefail" in NO_PIPEFAIL_NOTE and "last command's" in NO_PIPEFAIL_NOTE + + +def test_the_windows_guidance_makes_no_pipefail_promise_and_uses_no_posix_syntax() -> None: + from abstractcore.tools.common_tools import _execute_command_guidance + from abstractcore.tools.core import _validate_tool_metadata + + told = _execute_command_guidance("nt") + everything = " ".join([told["description"], told["when_to_use"], *(str(ex) for ex in told["examples"])]) + assert "pipefail" not in everything + assert "A pipeline (a | b) reports only its last command's exit code" in told["description"] + for posix_only_text in ("[ $? -eq 1 ]", "{ grep", "head", "/dev/null", "ls -la", "rm "): + assert posix_only_text not in everything, posix_only_text + # Over-long text raises at import, and only a Windows host would ever import it. + _validate_tool_metadata(name="execute_command", **told) + + +def test_the_shipped_tool_carries_the_guidance_of_the_platform_it_runs_on() -> None: + from abstractcore.tools.common_tools import _execute_command_guidance + + td = execute_command._tool_definition + here = _execute_command_guidance(os.name) + assert (td.description, td.when_to_use, td.examples) == (here["description"], here["when_to_use"], here["examples"]) + assert _execute_command_guidance("posix") != _execute_command_guidance("nt") + assert "pipelines use pipefail" in _execute_command_guidance("posix")["description"] diff --git a/tests/tools/test_posix_shell.py b/tests/tools/test_posix_shell.py new file mode 100644 index 00000000..e4a1e88f --- /dev/null +++ b/tests/tools/test_posix_shell.py @@ -0,0 +1,161 @@ +"""The shell a POSIX string command runs in (`sandbox.posix_shell`): bash with pipefail when the +host has it, else /bin/sh with pipefail only when that shell honours it, else /bin/sh without it +(reported, never silent). Resolved once per process. Fake shells under tmp_path stand in for +"no bash" and "a /bin/sh without pipefail" (dash before it gained the option).""" + +from __future__ import annotations + +import os +import stat +import subprocess +import sys + +import pytest + +from abstractcore.tools import sandbox as sb + +pytestmark = pytest.mark.skipif(os.name != "posix", reason="POSIX shell selection") + + +@pytest.fixture(autouse=True) +def _fresh_shell(): + sb._reset_posix_shell_for_tests() + yield + sb._reset_posix_shell_for_tests() + + +def _script(path, body: str) -> str: + path.write_text("#!/bin/sh\n" + body) + path.chmod(path.stat().st_mode | stat.S_IXUSR) + return str(path) + + +def _real_bash() -> str: + for cand in ("/bin/bash", "/usr/bin/bash"): + if os.access(cand, os.X_OK): + return cand + pytest.skip("no bash on this host") + + +# Stands in for a /bin/sh that honours pipefail (macOS bash-as-sh, Ubuntu's dash 0.5.12). +def _sh_with_pipefail(tmp_path, bash: str) -> str: + return _script(tmp_path / "sh", f'exec {bash} --posix "$@"\n') + + +# Refuses `-o pipefail` the way macOS's dash 0.5.11 does ("Illegal option -o pipefail", exit 2). +def _sh_without_pipefail(tmp_path) -> str: + return _script(tmp_path / "sh", 'if [ "$1" = "-o" ]; then echo "Illegal option -o $2" >&2; exit 2; fi\nexec /bin/sh "$@"\n') + + +def test_sh_with_pipefail_is_preferred_over_bash(tmp_path, monkeypatch): + # Each platform keeps its own /bin/sh semantics when that shell can do pipefail. + bash = _real_bash() + sh = _sh_with_pipefail(tmp_path, bash) + monkeypatch.setattr(sb, "_BASH_CANDIDATES", ("/nonexistent/bash", bash)) + monkeypatch.setattr(sb, "_POSIX_SH", sh) + assert sb.posix_shell() == ((sh, "-o", "pipefail", "-c"), True) + assert subprocess.run(list(sb.posix_shell()[0]) + ["false | true"]).returncode == 1 + + +def test_bash_posix_is_used_when_sh_lacks_pipefail(tmp_path, monkeypatch): + bash = _real_bash() + monkeypatch.setattr(sb, "_BASH_CANDIDATES", ("/nonexistent/bash", bash)) + monkeypatch.setattr(sb, "_POSIX_SH", _sh_without_pipefail(tmp_path)) + argv, pipefail = sb.posix_shell() + assert argv == (bash, "--posix", "-o", "pipefail", "-c") and pipefail is True + assert subprocess.run(list(sb.posix_shell()[0]) + ["false | true"]).returncode == 1 + + +def test_the_real_host_shell_honours_pipefail(): + argv, pipefail = sb.posix_shell() + assert pipefail is True, argv + assert subprocess.run(list(argv) + ["false | true"]).returncode == 1 + if sys.platform == "darwin": + assert argv == ("/bin/sh", "-o", "pipefail", "-c") # macOS /bin/sh is bash in POSIX mode + + +def test_sh_without_pipefail_is_reported(tmp_path, monkeypatch): + sh = _sh_without_pipefail(tmp_path) + monkeypatch.setattr(sb, "_BASH_CANDIDATES", ()) + monkeypatch.setattr(sb, "_POSIX_SH", sh) + assert sb.posix_shell() == ((sh, "-c"), False) + + +def test_neither_shell_reads_bash_env(tmp_path, monkeypatch): + marker = tmp_path / "bash_env_ran" + rc = tmp_path / "rc.sh" + rc.write_text(f"touch {marker}\n") + monkeypatch.setenv("BASH_ENV", str(rc)) + monkeypatch.setenv("ENV", str(rc)) + bash = _real_bash() + for argv in (sb.posix_shell()[0], (bash, "--posix", "-o", "pipefail", "-c")): + assert subprocess.run(list(argv) + ["true"]).returncode == 0 + assert not marker.exists(), argv + + +def test_an_accepted_but_ignored_option_is_not_pipefail(tmp_path, monkeypatch): + # The probe checks the BEHAVIOUR (a failing first stage decides the status), not only that + # the option is accepted. + sh = _script(tmp_path / "sh", 'if [ "$1" = "-o" ]; then shift 2; fi\nexec /bin/sh "$@"\n') + monkeypatch.setattr(sb, "_BASH_CANDIDATES", ()) + monkeypatch.setattr(sb, "_POSIX_SH", sh) + assert sb.posix_shell()[1] is False + + +def test_resolved_once_per_process(monkeypatch): + calls = [] + real = sb._honours_pipefail + + def counting(argv): + calls.append(tuple(argv)) + return real(argv) + + monkeypatch.setattr(sb, "_honours_pipefail", counting) + first = sb.posix_shell() + probes = len(calls) + assert probes >= 1 + for _ in range(5): + assert sb.posix_shell() == first + assert len(calls) == probes, calls + + +def test_a_probe_that_raised_is_not_cached(tmp_path, monkeypatch): + bash = _real_bash() + sh = _sh_with_pipefail(tmp_path, bash) + monkeypatch.setattr(sb, "_BASH_CANDIDATES", (bash,)) + monkeypatch.setattr(sb, "_POSIX_SH", sh) + real_run = subprocess.run + raised = [] + + def flaky_run(*args, **kwargs): + if not raised: + raised.append(True) + raise OSError(11, "Resource temporarily unavailable") # e.g. fork failed under load + return real_run(*args, **kwargs) + + monkeypatch.setattr(subprocess, "run", flaky_run) + # The sh probe raised, bash answered: used for this call, not remembered. + assert sb.posix_shell() == ((bash, "--posix", "-o", "pipefail", "-c"), True) + assert raised and sb._SHELL is None + assert sb.posix_shell() == ((sh, "-o", "pipefail", "-c"), True) + assert sb._SHELL is not None # a probe that answered is cached + + +def test_a_probe_killed_by_a_signal_is_not_cached(tmp_path, monkeypatch): + bash = _real_bash() + sh = _sh_with_pipefail(tmp_path, bash) + monkeypatch.setattr(sb, "_BASH_CANDIDATES", ()) + monkeypatch.setattr(sb, "_POSIX_SH", sh) + real_run = subprocess.run + killed = [] + + def killed_once(args, **kwargs): + if not killed: + killed.append(True) + return subprocess.CompletedProcess(args, -9) + return real_run(args, **kwargs) + + monkeypatch.setattr(subprocess, "run", killed_once) + assert sb.posix_shell() == ((sh, "-c"), False) # no answer: ran without pipefail, once + assert sb._SHELL is None + assert sb.posix_shell() == ((sh, "-o", "pipefail", "-c"), True) diff --git a/tests/tools/test_sandbox_linux.py b/tests/tools/test_sandbox_linux.py index 07119dd5..5bedc131 100644 --- a/tests/tools/test_sandbox_linux.py +++ b/tests/tools/test_sandbox_linux.py @@ -175,3 +175,27 @@ def test_landlock_allowed_child_of_a_refused_parent(nested, monkeypatch): assert (t / "home/parent/child/new.txt").exists() res = execute_command(f"cat {t}/home/parent/secret.txt", working_directory=str(t / "priv"), _sandbox=stamp) assert MARK not in (res.get("stdout") or "") + (res.get("stderr") or "") + + +# --- pipelines fail when any stage fails, inside the sandbox too (2026-11-17) ----------- + + +def _check_pipelines(t, posture, default_mode="rw"): + stamp = _stamp(t, posture, default_mode) + cwd = str(t / "priv") + res = execute_command("sh -c 'echo error: x; exit 101' 2>&1 | grep -E '^error' -A 7 | head -60", working_directory=cwd, _sandbox=stamp) + assert res["pipefail"] is True, res["rendered"] + assert res["success"] is False and res["return_code"] == 101 and "error: x" in res["stdout"], res["rendered"] + res = execute_command("printf 'a\\nb\\n' | grep b | cat", working_directory=cwd, _sandbox=stamp) + assert res["success"] is True and res["stdout"] == "b\n", res["rendered"] + + +@pytest.mark.parametrize("posture,default_mode", [("any_except_denied", "rw"), ("allowed_only", "rw")]) +def test_bwrap_pipeline_failure_is_reported(t, posture, default_mode): + _need_bwrap() + _check_pipelines(t, posture, default_mode) + + +def test_landlock_pipeline_failure_is_reported(t, monkeypatch): + _need_landlock(monkeypatch) + _check_pipelines(t, "allowed_only") diff --git a/tests/tools/test_sandbox_macos.py b/tests/tools/test_sandbox_macos.py index 92f34f74..c0623a49 100644 --- a/tests/tools/test_sandbox_macos.py +++ b/tests/tools/test_sandbox_macos.py @@ -244,24 +244,29 @@ def test_model_cannot_forge_wider_stamp_flag(t, monkeypatch): # --- persistent shell session ------------------------------------------------------------ +def _rendered(res) -> str: + assert isinstance(res, dict) and isinstance(res.get("rendered"), str), res + return res["rendered"] + + def test_shell_session_is_sandboxed_for_its_whole_life(t): stamp = _stamp(t, "allowed_only") ns = "r12-test" try: - out = shell_exec("cd /", _registry_namespace=ns, working_directory=str(t / "priv"), _sandbox=stamp) + out = _rendered(shell_exec("cd /", _registry_namespace=ns, working_directory=str(t / "priv"), _sandbox=stamp)) assert "Sandbox: macOS sandbox-exec" in out - out = shell_exec(f"cd {t}/refused; cat secret.txt; cat {t}/refused/secret.txt", _registry_namespace=ns, _sandbox=stamp) + out = _rendered(shell_exec(f"cd {t}/refused; cat secret.txt; cat {t}/refused/secret.txt", _registry_namespace=ns, _sandbox=stamp)) assert REFUSED_MARK not in out - out = shell_exec(f"cat {t}/home/outside/f.txt", _registry_namespace=ns, _sandbox=stamp) + out = _rendered(shell_exec(f"cat {t}/home/outside/f.txt", _registry_namespace=ns, _sandbox=stamp)) assert OUTSIDE_MARK not in out - out = shell_exec(f"cat {t}/ro/f.txt; echo hi > {t}/rw/s.txt && echo WROTE", _registry_namespace=ns, _sandbox=stamp) + out = _rendered(shell_exec(f"cat {t}/ro/f.txt; echo hi > {t}/rw/s.txt && echo WROTE", _registry_namespace=ns, _sandbox=stamp)) assert RO_MARK in out and "WROTE" in out # A different (wider) sandbox replaces the session: it never keeps old access, and a # narrower call never inherits a wider session either. wider = _stamp(t, "any_except_denied", refused=()) - out = shell_exec(f"cat {t}/refused/secret.txt", _registry_namespace=ns, _sandbox=wider) + out = _rendered(shell_exec(f"cat {t}/refused/secret.txt", _registry_namespace=ns, _sandbox=wider)) assert "new shell session" in out and REFUSED_MARK in out # positive control - out = shell_exec(f"cat {t}/refused/secret.txt", _registry_namespace=ns, _sandbox=stamp) + out = _rendered(shell_exec(f"cat {t}/refused/secret.txt", _registry_namespace=ns, _sandbox=stamp)) assert "new shell session" in out and REFUSED_MARK not in out finally: get_shell_session_registry().close_namespace(ns) @@ -269,8 +274,9 @@ def test_shell_session_is_sandboxed_for_its_whole_life(t): def test_shell_session_fails_closed(t, monkeypatch): monkeypatch.setattr(sb, "SANDBOX_EXEC", str(t / "no-such-sandbox-exec")) - out = shell_exec(f"cat {t}/refused/secret.txt", _registry_namespace="r12-fc", _sandbox=_stamp(t)) - assert out.startswith("Error: Commands are not sandboxed on this gateway host") + res = shell_exec(f"cat {t}/refused/secret.txt", _registry_namespace="r12-fc", _sandbox=_stamp(t)) + assert res["success"] is False and res["error"].startswith("Commands are not sandboxed on this gateway host") + assert res["rendered"].startswith("Error: Commands are not sandboxed on this gateway host") assert get_shell_session_registry().get("r12-fc::main") is None @@ -313,3 +319,42 @@ def test_allow_list_denies_unlisted_files_in_the_shared_temp_roots(t): import shutil shutil.rmtree(vf_dir, ignore_errors=True) + + +# --- pipelines fail when any stage fails, inside the sandbox too (2026-11-17) ----------- + + +@pytest.mark.parametrize("posture,default_mode", POSTURES) +def test_sandboxed_pipeline_failure_is_reported(t, posture, default_mode): + stamp = _stamp(t, posture, default_mode) + cmd = "sh -c 'echo error: x; exit 101' 2>&1 | grep -E '^error' -A 7 | head -60" + res, _ = _run(t, cmd, stamp) + assert res["sandbox"]["kind"] == "macos-sandbox-exec" + assert res["pipefail"] is True + assert res["success"] is False and res["return_code"] == 101, res["rendered"] + assert "error: x" in res["stdout"] + assert res["rendered"].endswith("❌ Command failed (exit code 101)") + + +@pytest.mark.parametrize("posture,default_mode", POSTURES) +def test_sandboxed_pipeline_success_and_sigpipe(t, posture, default_mode): + stamp = _stamp(t, posture, default_mode) + res, _ = _run(t, "printf 'a\\nb\\n' | grep b | cat", stamp) + assert res["success"] is True and res["return_code"] == 0 and res["stdout"] == "b\n", res["rendered"] + res, _ = _run(t, "yes | head -n 1", stamp) + assert res["success"] is False and res["return_code"] == 141, res["rendered"] + assert "killed by SIGPIPE" in res["error"] + + +def test_sandboxed_call_resolves_the_shell_once(t, monkeypatch): + calls = [] + answers = iter([(("/bin/sh", "-c"), False), (("/bin/sh", "-o", "pipefail", "-c"), True)]) + + def flaky(): + calls.append(1) + return next(answers) + + monkeypatch.setattr(sb, "posix_shell", flaky) + res, _ = _run(t, "sh -c 'exit 3' | cat", _stamp(t)) + assert len(calls) == 1 + assert res["pipefail"] is False and res["return_code"] == 0, res["rendered"] diff --git a/tests/tools/test_sandbox_spec.py b/tests/tools/test_sandbox_spec.py index 2aec7d5c..ce7fbce9 100644 --- a/tests/tools/test_sandbox_spec.py +++ b/tests/tools/test_sandbox_spec.py @@ -32,6 +32,17 @@ def _fresh_host(): sb._reset_host_for_tests() +# The shell a string command runs in, pinned so no probe runs here (test_posix_shell.py +# covers the resolution itself). +BASH_PIPEFAIL = ("/bin/bash", "--posix", "-o", "pipefail", "-c") + + +@pytest.fixture +def pinned_shell(monkeypatch): + monkeypatch.setattr(sb, "_SHELL", (BASH_PIPEFAIL, True)) + return list(BASH_PIPEFAIL) + + @pytest.fixture def tree(tmp_path, monkeypatch): home = tmp_path / "home" @@ -152,13 +163,13 @@ def test_no_sandbox_binary_fails_closed(tree, monkeypatch): assert res["success"] is False and res["sandbox"]["kind"] == "none" -def test_host_flag_reenables_unsandboxed(tree, monkeypatch): +def test_host_flag_reenables_unsandboxed(tree, monkeypatch, pinned_shell): monkeypatch.setattr(sb, "host_sandbox_kind", lambda posture="allowed_only": KIND_NONE) configure_host(env={"PATH": "/usr/bin"}, unsandboxed_commands_allowed=True) box = sandbox_for_tool_call(_spec(tree).to_stamp()) assert box.kind == KIND_UNSANDBOXED and not box.refuses argv, env = box.wrap("echo hi") - assert argv == ["/bin/sh", "-c", "echo hi"] and env["PATH"] == "/usr/bin" + assert argv == pinned_shell + ["echo hi"] and env["PATH"] == "/usr/bin" def test_macos_missing_sandbox_exec_is_none(monkeypatch): @@ -223,6 +234,9 @@ def test_windows_wraps_commands_with_the_launcher(tree, monkeypatch): assert json.loads(zlib.decompress(base64.urlsafe_b64decode(argv[3]))) == {"rules": sb.windows_rules(_spec(tree)), "state": str(tree / "machine/state")} assert argv[4:] == ["--shell", "echo hi"] # one string: the launcher runs it as `shell=True` does + # The launcher's shell is the only one this sandbox has: a caller's POSIX shell (what + # execute_command resolves on macOS and Linux) is never put in front of the command. + assert box.wrap("echo hi", shell=("/bin/sh", "-o", "pipefail", "-c"))[0][4:] == ["--shell", "echo hi"] assert box.wrap(["git", "status"])[0][4:] == ["--", "git", "status"] assert env["TEMP"] == env["TMP"] == str(tree / "priv" / ".tmp") with pytest.raises(SandboxError): @@ -456,10 +470,16 @@ def test_profile_posture_floor(tree): assert '(deny file-write* (subpath "/"))' in prof_any_ro -def test_profile_never_parses_the_command(tree): +def test_profile_never_parses_the_command(tree, pinned_shell): box = sb.Sandbox(kind=sb.KIND_MACOS, spec=_spec(tree), _prefix=("/usr/bin/sandbox-exec", "-p", "PROFILE")) argv, _ = box.wrap("cat $(echo x) && cd .. ; ls") - assert argv == ["/usr/bin/sandbox-exec", "-p", "PROFILE", "/bin/sh", "-c", "cat $(echo x) && cd .. ; ls"] + assert argv == ["/usr/bin/sandbox-exec", "-p", "PROFILE"] + pinned_shell + ["cat $(echo x) && cd .. ; ls"] + # An argv list runs as given (no shell, no pipefail prefix). + argv, _ = box.wrap(["ls", "-la"]) + assert argv == ["/usr/bin/sandbox-exec", "-p", "PROFILE", "ls", "-la"] + # The caller's already-resolved shell is used as given (one resolution per call). + argv, _ = box.wrap("ls", shell=("/x/sh", "-o", "pipefail", "-c")) + assert argv == ["/usr/bin/sandbox-exec", "-p", "PROFILE", "/x/sh", "-o", "pipefail", "-c", "ls"] # --- bwrap / Landlock rule generation ---------------------------------------------------- @@ -491,7 +511,7 @@ def test_bwrap_argv_order_and_masks(tree): assert ["--bind", "/", "/"] != allow_argv[2:5] and "/home" not in allow_argv -def test_landlock_refuses_what_it_cannot_express(tree, monkeypatch): +def test_landlock_refuses_what_it_cannot_express(tree, monkeypatch, pinned_shell): monkeypatch.setattr(sb, "host_sandbox_kind", lambda posture="allowed_only": sb.KIND_LANDLOCK) nested = _spec(tree, posture="allowed_only", allowed=(SandboxRow(str(tree / "allowed"), "rw"),), refused=(str(tree / "allowed/sub"),)) box = build_sandbox(nested) @@ -500,7 +520,7 @@ def test_landlock_refuses_what_it_cannot_express(tree, monkeypatch): ok = build_sandbox(flat) assert ok.kind == sb.KIND_LANDLOCK argv, _ = ok.wrap("ls") - assert argv[1:3] == ["-m", "abstractcore.tools.sandbox"] and argv[-3:] == ["/bin/sh", "-c", "ls"] + assert argv[1:3] == ["-m", "abstractcore.tools.sandbox"] and argv[-6:] == pinned_shell + ["ls"] rules = dict(json.loads(argv[3])) assert rules[str(tree / "rw")] == "rw" and rules[str(tree / "ro")] == "ro" assert str(tree / "refused") not in rules @@ -541,3 +561,22 @@ def test_landlock_grants_an_allowed_child_of_a_refused_parent(tree, monkeypatch) rules = dict(sb.landlock_rules(spec)) assert rules[str(tree / "parent/child")] == "rw" assert str(tree / "parent") not in rules + + +# --- what execute_command tells the model, on the host that runs these tests ----------------- + + +def test_execute_command_tells_the_model_about_the_platform_it_runs_on(): + """This file runs in the Windows job too (ci.yml, `windows-sandbox`): the one place where a + host that really is Windows proves it ships the cmd.exe text and not the POSIX one.""" + from abstractcore.tools.common_tools import _execute_command_guidance, execute_command + + td = execute_command._tool_definition + here = _execute_command_guidance(os.name) + assert (td.description, td.when_to_use, td.examples) == (here["description"], here["when_to_use"], here["examples"]) + told = " ".join([td.description, td.when_to_use, *(str(ex) for ex in td.examples)]) + if os.name == "nt": + assert "pipefail" not in told, told + assert "reports only its last command's exit code" in td.description + else: + assert "pipelines use pipefail" in td.description diff --git a/tests/tools/test_shell_session.py b/tests/tools/test_shell_session.py index 39bdc5ec..914b1777 100644 --- a/tests/tools/test_shell_session.py +++ b/tests/tools/test_shell_session.py @@ -1,11 +1,16 @@ """Persistent shell session (backlog 0215).""" from __future__ import annotations +import os import shutil +import signal +import subprocess +import threading +import time import pytest -from abstractcore.tools.shell_session import ShellSessionRegistry +from abstractcore.tools.shell_session import ShellCommandResult, ShellSession, ShellSessionRegistry _HAS_SHELL = bool(shutil.which("bash") or shutil.which("sh")) pytestmark = pytest.mark.skipif(not _HAS_SHELL, reason="no POSIX shell available") @@ -153,8 +158,9 @@ def test_large_output_returns_exit_code_not_false_timeout(tmp_path) -> None: reg = ShellSessionRegistry() sess = reg.open(cwd=str(tmp_path)) try: - # ~2 MB of output on stdout, then exits 0. - r = sess.run("yes ABCDEFGHIJ | head -n 200000", timeout_s=20) + # ~2 MB of output on stdout, then exits 0. (Not `yes | head`: under pipefail `yes` is cut + # off by SIGPIPE and the pipeline honestly exits 141.) + r = sess.run("awk 'BEGIN { for (i = 0; i < 200000; i++) print \"ABCDEFGHIJ\" }'", timeout_s=20) assert r.timed_out is False, "large output should not false-timeout" assert r.exit_code == 0 assert r.truncated is True # bounded to the preview cap @@ -298,10 +304,13 @@ def _open_fd_count() -> int: # waitpid(WNOHANG) sees the child gone (observed under a loaded CI matrix, # 2026-11-08). Wait for that exit itself, which the SIGKILL makes certain, # instead of a deadline; is_alive() then reports the reaped shell as dead. + # run() reaps a shell that ended during its command and forgets the pid (None). import contextlib - with contextlib.suppress(ChildProcessError): # run() may have reaped it already - os.waitpid(s._pid, 0) + pid = s._pid + if pid is not None: + with contextlib.suppress(ChildProcessError): + os.waitpid(pid, 0) assert s.is_alive() is False if i == 1: baseline = _open_fd_count() @@ -363,3 +372,761 @@ def test_close_namespace_only_reaps_that_namespace(tmp_path) -> None: assert reg.get(namespaced_session_id("run-b", "main")) is not None finally: reg.close_all() + + +def test_session_pipelines_use_pipefail(tmp_path) -> None: + # 2026-11-17: the operator's failing `cargo build | grep | head` reported exit 0 in shell_exec too. + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + try: + assert sess.pipefail is True + r = sess.run("sh -c 'echo error: x; exit 101' 2>&1 | grep -E '^error' -A 7 | head -60") + assert r.exit_code == 101 and "error: x" in r.stdout and r.pipefail is True + ok = sess.run("printf 'a\\nb\\n' | grep b | cat") + assert ok.exit_code == 0 and ok.stdout.strip() == "b" + finally: + reg.close_all() + + +def test_shell_exec_renders_the_failure_like_execute_command(tmp_path) -> None: + from abstractcore.tools import shell_tools + + res = shell_tools.shell_exec("sh -c 'exit 3' | cat", session_id="pf_render", working_directory=str(tmp_path)) + try: + out = res["rendered"] + assert res["success"] is False and res["return_code"] == res["exit_code"] == 3 and res["pipefail"] is True + assert res["error"] == "Command failed (exit code 3)" + assert "exit_code: 3" in out + assert out.endswith("(no output)\n❌ Command failed (exit code 3)") + assert "pipefail" not in out # on, so nothing to warn about + ok = shell_tools.shell_exec("echo fine", session_id="pf_render") + assert ok["success"] is True and ok["error"] is None + assert "❌" not in ok["rendered"] and "fine" in ok["rendered"] + finally: + shell_tools.get_shell_session_registry().close_all() + + +def test_shell_exec_when_to_use_teaches_the_grouped_idioms() -> None: + from abstractcore.tools import shell_tools + + w = shell_tools.shell_exec._tool_definition.when_to_use + assert "Never pipe into head" in w + assert "cmd | { grep pat || [ $? -eq 1 ]; }" in w and "cmd | { grep pat >/dev/null && echo y || echo n; }" in w + + +def test_pipefail_survives_a_command_that_turns_it_off(tmp_path) -> None: + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + try: + assert sess.pipefail is True + sess.run("set +o pipefail") + r = sess.run("false | true") + assert r.exit_code == 1 and r.pipefail is True + finally: + reg.close_all() + + +@pytest.mark.skipif(not os.access("/bin/dash", os.X_OK), reason="no /bin/dash on this host") +def test_a_real_dash_session_reports_what_it_measured(tmp_path) -> None: + # The session's pipefail is measured in the session, never assumed from the shell's name. + sess = ShellSession(session_id="dash_probe", shell_path="/bin/dash", cwd=str(tmp_path)) + sess.start() + try: + r = sess.run("false | true") + honours = subprocess.run(["/bin/dash", "-c", "set -o pipefail 2>/dev/null && false | true"]).returncode == 1 + assert sess.pipefail is honours and r.pipefail is honours + assert r.exit_code == (1 if honours else 0) + finally: + sess.close() + + +def test_unknown_pipefail_is_said_as_unknown() -> None: + from abstractcore.tools import shell_tools + + unknown = shell_tools._render_result(ShellCommandResult(stdout="x", exit_code=0, pipefail=None)) + assert "whether this shell has pipefail is unknown" in unknown + off = shell_tools._render_result(ShellCommandResult(stdout="x", exit_code=0, pipefail=False)) + assert "this shell has no pipefail" in off + on = shell_tools._render_result(ShellCommandResult(stdout="x", exit_code=0, pipefail=True)) + assert "pipefail" not in on + + +def test_start_probe_that_times_out_leaves_pipefail_unknown(tmp_path, monkeypatch) -> None: + real = ShellSession._run_raw + + def slow_probe(self, command, *, timeout_s): + if command == "false | true": + return ShellCommandResult(stdout="", exit_code=None, timed_out=True) + return real(self, command, timeout_s=timeout_s) + + monkeypatch.setattr(ShellSession, "_run_raw", slow_probe) + sess = ShellSession(session_id="slow_probe", shell_path=shutil.which("bash") or "/bin/sh", cwd=str(tmp_path)) + sess.start() + try: + assert sess.pipefail is None + finally: + sess.close() + + +def test_long_failing_session_output_keeps_its_tail(tmp_path) -> None: + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + try: + # ~2 MB, then the error at the very end: past the reader's head cap (bounded mode). + cmd = "awk 'BEGIN { for (i = 0; i < 200000; i++) print \"filler\" i }'; echo FINAL_SESSION_ERROR; (exit 2)" + r = sess.run(cmd, timeout_s=30) + assert r.exit_code == 2 and r.truncated is True + full = "".join(f"filler{i}\n" for i in range(200000)) + "FINAL_SESSION_ERROR\n" + assert r.stdout == f"{full[:5000]}\n... ({len(full) - 20000} chars omitted) ...\n{full[-15000:]}" + # Just over the preview cap (complete in the reader): same split. + r = sess.run("awk 'BEGIN { for (i = 0; i < 2800; i++) print \"mid\" i }'; echo FINAL_SMALL_ERROR; (exit 4)", timeout_s=30) + full = "".join(f"mid{i}\n" for i in range(2800)) + "FINAL_SMALL_ERROR\n" + assert r.exit_code == 4 + assert r.stdout == f"{full[:5000]}\n... ({len(full) - 20000} chars omitted) ...\n{full[-15000:]}" + # A successful long output keeps its head only (unchanged). + ok = sess.run("awk 'BEGIN { for (i = 0; i < 200000; i++) print \"filler\" i }'; echo FINAL_OK", timeout_s=30) + assert ok.exit_code == 0 and "FINAL_OK" not in ok.stdout + finally: + reg.close_all() + + +# --- a command that ends the session shell is a failure (2026-11-17 re-gate) ---------------- + + +@pytest.mark.parametrize( + "commands,code", + [ + (["set -euo pipefail", "false"], 1), + (["printf 'echo sourcing\\nexit 1\\n' > setup.sh", ". ./setup.sh"], 1), + (["exit 3"], 3), + ], +) +def test_a_command_that_ends_the_shell_fails(tmp_path, commands, code) -> None: + from abstractcore.tools import shell_tools + + ns = f"ended-{code}-{len(commands)}" + try: + for c in commands[:-1]: + assert shell_tools.shell_exec(c, working_directory=str(tmp_path), _registry_namespace=ns)["success"] is True + res = shell_tools.shell_exec(commands[-1], working_directory=str(tmp_path), _registry_namespace=ns) + assert res["success"] is False and res["session_ended"] is True + assert res["return_code"] == code + assert res["error"].startswith(f"The shell session ended during this command (exit code {code})") + assert res["rendered"].endswith(f"❌ {res['error']}") + again = shell_tools.shell_exec("echo back", _registry_namespace=ns) + assert again["success"] is True and "new shell session" in again["rendered"] + finally: + shell_tools.get_shell_session_registry().close_namespace(ns) + + +def test_a_timeout_keeps_the_latest_output(tmp_path) -> None: + from abstractcore.tools import shell_tools + + ns = "timeout-tail" + cmd = "awk 'BEGIN { for (i = 0; i < 9000; i++) print \"line_\" i \"_xxx\" }'; echo LAST_BEFORE_SLEEP; sleep 30" + try: + res = shell_tools.shell_exec(cmd, timeout=3, working_directory=str(tmp_path), _registry_namespace=ns) + assert res["success"] is False and res["timed_out"] is True + assert "timed out after 3s" in res["error"] + assert "LAST_BEFORE_SLEEP" in res["rendered"] and "line_0_xxx" in res["rendered"] + finally: + shell_tools.get_shell_session_registry().close_namespace(ns) + + +def test_exec_into_a_shell_without_pipefail_stops_claiming_it(tmp_path) -> None: + if not os.access("/bin/dash", os.X_OK): + pytest.skip("no /bin/dash on this host") + if subprocess.run(["/bin/dash", "-c", "set -o pipefail 2>/dev/null"]).returncode == 0: + pytest.skip("this host's dash has pipefail") + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + try: + assert sess.pipefail is True + sess.run("exec /bin/dash") + r = sess.run("false | true") + assert sess.pipefail is False and r.pipefail is False and r.exit_code == 0 + assert "Illegal option" not in r.stdout and r.stdout == "" + finally: + reg.close_all() + + +def test_a_failing_shell_exec_is_a_failure_for_the_registry_and_the_runtime(tmp_path) -> None: + from abstractcore.tools import shell_tools + from abstractcore.tools.core import ToolCall + from abstractcore.tools.registry import ToolRegistry + + ns = "registry-verdict" + try: + registry = ToolRegistry() + registry.register(shell_tools.shell_exec) + bad = registry.execute_tool(ToolCall(name="shell_exec", arguments={"command": "sh -c 'exit 5' | cat", "_registry_namespace": ns}, call_id="c1")) + assert bad.success is False and "exit code 5" in str(bad.error) + ok = registry.execute_tool(ToolCall(name="shell_exec", arguments={"command": "echo fine", "_registry_namespace": ns}, call_id="c2")) + assert ok.success is True + try: + from abstractruntime.integrations.abstractcore.tool_executor import MappingToolExecutor + except Exception: + return # abstractruntime is not installed next to abstractcore here + out = MappingToolExecutor.from_tools([shell_tools.shell_exec]).execute( + tool_calls=[{"name": "shell_exec", "arguments": {"command": "sh -c 'exit 6' | cat", "_registry_namespace": ns}, "call_id": "c3"}] + ) + res = out["results"][0] + assert res["success"] is False and "exit code 6" in res["error"] + assert "❌ Command failed (exit code 6)" in res["output"]["rendered"] + finally: + shell_tools.get_shell_session_registry().close_namespace(ns) + + +# --- review round 5 (2026-11-17) -------------------------------------------------------------- + + +def _exec(cmd: str, ns: str, **kw): + from abstractcore.tools import shell_tools + + return shell_tools.shell_exec(cmd, _registry_namespace=ns, **kw) + + +def _close(ns: str) -> None: + from abstractcore.tools.shell_session import get_shell_session_registry + + get_shell_session_registry().close_namespace(ns) + + +@pytest.mark.parametrize( + "before,cmd,success,code", + [ + # A line left open is a syntax error at the group's `}`: a failure, never a stale status. + ("true", "sh -c 'exit 2' 2>&1 &&", False, None), + ("(exit 7)", "true ||", False, None), + ("true", "echo hello |", False, None), # its output is not swallowed into a success + ("true", "f()", False, None), + ("true", "if true; then echo x", False, None), + ("true", "sh -c 'exit 4' \\", False, 4), # a trailing backslash keeps its status + ], +) +def test_a_command_line_left_open_never_reports_a_stale_status(tmp_path, before, cmd, success, code) -> None: + ns = f"open-line-{abs(hash(cmd))}" + try: + _exec(before, ns, working_directory=str(tmp_path)) + res = _exec(cmd, ns, timeout=10) + assert res["timed_out"] is False + assert res["success"] is success, res + if code is not None: + assert res["return_code"] == code + assert _exec("echo next", ns)["success"] is True + finally: + _close(ns) + + +def test_an_unreadable_exit_code_is_a_failure() -> None: + from abstractcore.tools import shell_tools + + r = ShellCommandResult(stdout="x", exit_code=None, exit_code_unreadable=True) + assert shell_tools._failure(r) == "Command failed: its exit code could not be read, so it is not reported as a success" + assert shell_tools._render_result(r).endswith("❌ " + shell_tools._failure(r)) + + +def test_reap_kills_the_group_before_freeing_the_pid_and_close_never_signals_it(monkeypatch) -> None: + from abstractcore.tools import shell_session as ss + + calls = [] + monkeypatch.setattr(ss.os, "killpg", lambda pid, sig: calls.append(("killpg", pid, sig))) + monkeypatch.setattr(ss.os, "kill", lambda pid, sig: calls.append(("kill", pid, sig))) + monkeypatch.setattr(ss.os, "getpgid", lambda pid: pid) + monkeypatch.setattr(ss.os, "waitpid", lambda pid, flags: calls.append(("waitpid", pid, flags)) or (pid, 3 << 8)) + sess = ss.ShellSession(session_id="fake", shell_path="/bin/sh") + sess._pid = 424242 + assert sess._reap() == 3 + assert calls == [("killpg", 424242, ss.signal.SIGKILL), ("waitpid", 424242, 0)] + assert sess._pid is None and sess._exit_status == 3 + calls.clear() + sess.close() + assert calls == [] # the freed pid is never signalled + assert sess._reap() == 3 + + +def test_is_alive_that_reaps_keeps_the_status_and_forgets_the_pid(tmp_path) -> None: + sess = ShellSession(session_id="alive_reap", shell_path=shutil.which("bash") or "/bin/sh", cwd=str(tmp_path)) + sess.start() + try: + sess._write("exit 6\n") + deadline = time.monotonic() + 10 + while sess.is_alive() and time.monotonic() < deadline: + time.sleep(0.05) + assert sess._pid is None and sess._exit_status == 6 + assert sess._reap() == 6 + finally: + sess.close() + + +def test_a_concurrent_is_alive_does_not_lose_the_exit_code(tmp_path) -> None: + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + stop = threading.Event() + + def spin(): + while not stop.is_set(): + sess.is_alive() + + t = threading.Thread(target=spin, daemon=True) + t.start() + try: + r = sess.run("exit 5", timeout_s=10) + assert r.session_ended is True and r.exit_code == 5 + finally: + stop.set() + t.join(timeout=5) + reg.close_all() + + +def test_pipefail_is_back_after_a_timeout(tmp_path) -> None: + ns = "timeout-pipefail" + try: + res = _exec("set +o pipefail; sleep 30", ns, timeout=2, working_directory=str(tmp_path)) + assert res["timed_out"] is True + after = _exec("false | true", ns, timeout=10) + assert after["success"] is False and after["return_code"] == 1 and after["pipefail"] is True + finally: + _close(ns) + + +def test_readonly_and_nounset_cannot_break_the_status_line(tmp_path) -> None: + ns = "readonly-status" + try: + assert _exec("readonly __abstract_rc __abstract_pf 2>/dev/null; set -u; true", ns, working_directory=str(tmp_path))["success"] is True + res = _exec("false", ns, timeout=10) + assert res["timed_out"] is False and res["success"] is False and res["return_code"] == 1 + assert _exec("echo ok", ns, timeout=10)["success"] is True + finally: + _close(ns) + + +def test_a_signal_that_ends_the_session_is_named(tmp_path) -> None: + ns = "signal-ended" + try: + res = _exec("kill -KILL $$", ns, timeout=10, working_directory=str(tmp_path)) + assert res["success"] is False and res["session_ended"] is True and res["return_code"] == -9 + assert "(exit code -9: terminated by SIGKILL)" in res["error"] + finally: + _close(ns) + + +def test_crlf_output_counts_the_normalised_text(tmp_path) -> None: + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + try: + r = sess.run("awk 'BEGIN { for (i = 0; i < 200000; i++) printf \"filler%d\\r\\n\", i }'; (exit 2)", timeout_s=30) + full = "".join(f"filler{i}\n" for i in range(200000)) + assert r.exit_code == 2 + assert r.stdout == f"{full[:5000]}\n... ({len(full) - 20000} chars omitted) ...\n{full[-15000:]}" + finally: + reg.close_all() + + +def test_exit_0_ending_the_session_is_still_a_failure(tmp_path) -> None: + ns = "exit-zero" + try: + res = _exec("exit 0", ns, working_directory=str(tmp_path)) + assert res["success"] is False and res["session_ended"] is True and res["return_code"] == 0 + assert "(exit code 0)" in res["error"] and "is lost" in res["error"] + finally: + _close(ns) + + +def test_shell_exec_refusals_are_failure_dicts(monkeypatch) -> None: + from abstractcore.tools import shell_tools + + empty = shell_tools.shell_exec(" ") + assert empty == {"success": False, "error": "command must be a non-empty string", "command": "", "rendered": "Error: command must be a non-empty string"} + + class Broken: + def get(self, key): + return None + + def open(self, **kw): + raise RuntimeError("no pty") + + monkeypatch.setattr(shell_tools, "get_shell_session_registry", lambda: Broken()) + failed = shell_tools.shell_exec("echo hi") + assert failed["success"] is False and failed["error"] == "shell session failed: no pty" + assert failed["rendered"] == "Error: shell session failed: no pty" + + +def test_write_stdin_that_ends_the_session_is_a_failure(tmp_path) -> None: + from abstractcore.tools import shell_tools + + ns = "stdin-ends" + try: + assert _exec("sleep 2", ns, timeout=1, working_directory=str(tmp_path))["timed_out"] is True + res = shell_tools.shell_write_stdin("exit 3", read_timeout=10, _registry_namespace=ns) + assert res["success"] is False and res["session_ended"] is True and res["return_code"] == 3 + assert res["error"].startswith("The shell session ended during this command (exit code 3)") + missing = shell_tools.shell_write_stdin("hi", _registry_namespace="nowhere-r5") + assert missing["success"] is False and "no active shell session" in missing["error"] + finally: + _close(ns) + + +# --- review round 6 (2026-11-17) -------------------------------------------------------------- + + +def test_a_prompt_reads_the_status_line_as_its_answer_and_the_call_times_out(tmp_path) -> None: + # What really happens (review 2026-11-29): the tool's status line waits in the terminal's + # input queue while the command runs, so a prompt reads it as its answer and carries on with + # it; no status line is left to print, so the call waits out its timeout. The model is told. + from abstractcore.tools import shell_tools + + ns = "prompt" + try: + asked = "read -p 'Proceed? [Y/n] ' a; case \"${a:-Y}\" in Y|y) echo PROCEEDED;; *) echo ABORTED;; esac" + res = _exec(asked, ns, timeout=2, working_directory=str(tmp_path)) + assert res["success"] is False and res["timed_out"] is True + assert "ABORTED" in res["rendered"] and "PROCEEDED" not in res["rendered"] # answered: with the status line + # The command has ended, so the next call finds an idle shell: it runs, in the same session. + after = _exec("echo after", ns, timeout=10) + assert after["success"] is True and after["rendered"] == "exit_code: 0\nafter\n" + res = _exec("read -n 1 -s -p 'Press any key to deploy' k; echo DEPLOYED", ns, timeout=2) + assert res["success"] is False and res["timed_out"] is True and "DEPLOYED" in res["rendered"] + # Nothing is waiting for input any more, and the timeout text does not say to feed it. + assert "If it is still waiting for input, feed it with shell_write_stdin" in res["rendered"] + assert "feed it with shell_write_stdin if it is still waiting for input" in res["error"] + typed = shell_tools.shell_write_stdin("y", read_timeout=5, _registry_namespace=ns) + assert "not found" in typed["rendered"] # the shell itself ran `y` as a command + # The taught form: the answer travels in the command, and the call returns with it. + fed = _exec("echo y | { " + asked + " }", ns, timeout=10) + assert fed["success"] is True and "PROCEEDED" in fed["rendered"] + description = shell_tools.shell_exec._tool_definition.description + assert "A prompt reads the tool's status line as its answer" in description and "echo y | cmd" in description + finally: + _close(ns) + + +def test_a_later_prompt_of_the_same_command_is_answered_with_shell_write_stdin(tmp_path) -> None: + from abstractcore.tools import shell_tools + + ns = "second-prompt" + try: + res = _exec("read -p 'first? ' a; read -p 'second? ' b; echo \"b=$b\"", ns, timeout=2, working_directory=str(tmp_path)) + assert res["timed_out"] is True and "second? " in res["rendered"] and "b=" not in res["rendered"] + answered = shell_tools.shell_write_stdin("yes", read_timeout=10, _registry_namespace=ns) + assert answered["success"] is True and "b=yes" in answered["rendered"] + finally: + _close(ns) + + +def test_a_shadowed_exit_cannot_turn_a_failure_into_success(tmp_path) -> None: + ns = "shadowed-exit" + try: + assert _exec("exit() { :; }; alias exit=true; alias false=true 2>/dev/null; :", ns, working_directory=str(tmp_path))["success"] is True + res = _exec("sh -c 'exit 9'", ns, timeout=10) + assert res["success"] is False and res["return_code"] == 9 + assert _exec("command false", ns, timeout=10)["return_code"] == 1 + finally: + _close(ns) + + +def test_set_e_with_a_failing_and_list_keeps_the_session(tmp_path) -> None: + ns = "set-e-and" + try: + res = _exec("set -e; false && true", ns, timeout=10, working_directory=str(tmp_path)) + assert res["success"] is False and res["return_code"] == 1 and res["session_ended"] is False + assert _exec("echo still", ns, timeout=10)["success"] is True + finally: + _close(ns) + + +def test_a_status_line_without_a_code_fails_the_call(tmp_path, monkeypatch) -> None: + from abstractcore.tools import shell_session as ss + from abstractcore.tools import shell_tools + + sess = ShellSession(session_id="no_code", shell_path=shutil.which("bash") or "/bin/sh", cwd=str(tmp_path)) + sess.start() + try: + monkeypatch.setattr(ss.ShellSession, "_read_until_sentinel", lambda self, sentinel, *, deadline: ss._Read("out", None, False, None, 3, False, None)) + r = sess.run("echo hi", timeout_s=5) + assert r.exit_code is None and r.exit_code_unreadable is True + assert shell_tools._failure(r) is not None + finally: + sess.close() + + +def test_history_expansion_is_off(tmp_path) -> None: + ns = "no-history" + try: + res = _exec('echo "Hello, World!"', ns, timeout=10, working_directory=str(tmp_path)) + assert res["success"] is True and "Hello, World!" in res["rendered"] and "event not found" not in res["rendered"] + res = _exec('echo "#!/bin/sh" > a.sh', ns, timeout=10) + assert res["success"] is True and (tmp_path / "a.sh").read_text() == "#!/bin/sh\n" + finally: + _close(ns) + + +def test_a_literal_tab_reaches_the_command(tmp_path) -> None: + ns = "literal-tab" + try: + cmd = "cat > Makefile <<'EOF'\nall:\n\techo built\nEOF" + res = _exec(cmd, ns, timeout=10, working_directory=str(tmp_path)) + assert res["success"] is True, res["rendered"] + assert (tmp_path / "Makefile").read_text() == "all:\n\techo built\n" + finally: + _close(ns) + + +def test_no_echo_even_when_the_parent_is_slow_to_configure_the_terminal(tmp_path, monkeypatch) -> None: + import termios + + parent = os.getpid() + real = termios.tcgetattr + + def slow_in_parent(fd): + if os.getpid() == parent: + time.sleep(1.5) # the shell and its line editor start before the parent gets here + return real(fd) + + monkeypatch.setattr(termios, "tcgetattr", slow_in_parent) + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + try: + r = sess.run("echo XYZZY_MARKER") + assert r.stdout == "XYZZY_MARKER\n", r.stdout + r = sess.run("pwd") + assert r.stdout.strip().endswith(os.path.basename(str(tmp_path))) and "pwd" not in r.stdout + finally: + reg.close_all() + + +def test_the_reassert_trace_never_reaches_the_next_call(tmp_path) -> None: + ns = "xtrace" + try: + _exec("set -x; trap 'echo DEBUG_TRAP_RAN' DEBUG", ns, timeout=10, working_directory=str(tmp_path)) + res = _exec("echo clean", ns, timeout=10) + assert res["success"] is True + assert "pipefail" not in res["rendered"].split("\n+ echo clean", 1)[0] + finally: + _close(ns) + + +def test_is_alive_kills_the_group_before_reaping_a_shell_whose_terminal_closed(monkeypatch) -> None: + from abstractcore.tools import shell_session as ss + + calls = [] + monkeypatch.setattr(ss.os, "killpg", lambda pid, sig: calls.append(("killpg", pid))) + monkeypatch.setattr(ss.os, "waitpid", lambda pid, flags: calls.append(("waitpid", pid, flags)) or (pid, 2 << 8)) + sess = ss.ShellSession(session_id="fake_alive", shell_path="/bin/sh") + sess._pid = 434343 + sess._pty_closed.set() + assert sess.is_alive() is False + assert calls == [("killpg", 434343), ("waitpid", 434343, 0)] + assert sess._pid is None and sess._exit_status == 2 + + +# --- merged with 2.40.0's resync (a session that cannot resynchronise is closed) ----------------- + + +def test_shell_exec_says_a_session_closed_after_a_failed_resync_and_the_next_call_starts_fresh(tmp_path, monkeypatch) -> None: + from abstractcore.tools import shell_session + from abstractcore.tools.shell_session import get_shell_session_registry, namespaced_session_id + + # The child ignores SIGINT, so no attempt's marker can ever print: any limit gives this outcome. + monkeypatch.setattr(shell_session, "_RESYNC_ATTEMPT_TIMEOUT_S", 0.5) + ns = "resync-closed" + try: + assert _exec("true", ns, timeout=10, working_directory=str(tmp_path))["success"] is True + _start_child(get_shell_session_registry().get(namespaced_session_id(ns, "main")), _IGNORES_INTERRUPTS) + res = _exec("echo FRESH_ONLY", ns, timeout=5) + assert res["success"] is False and res["command"] == "echo FRESH_ONLY" + assert res["error"].startswith("shell session failed: ") and "could not be resynchronised" in res["error"] + assert res["rendered"] == "Error: " + res["error"] + fresh = _exec("echo FRESH_ONLY", ns, timeout=10) + assert fresh["success"] is True and fresh["return_code"] == 0 + assert "new shell session 'main' started" in fresh["rendered"] + assert fresh["rendered"].endswith("FRESH_ONLY\n") and "STALE" not in fresh["rendered"] + finally: + _close(ns) + + +# --- review of the merge (2026-11-29) --------------------------------------------------------- + + +@pytest.mark.parametrize( + "command, code, named", + [ + ("exec sleep 100", -signal.SIGINT, "(exit code -2: terminated by SIGINT)"), # the shell IS the sleep + ("trap 'exit 9' INT; sleep 100", 9, "(exit code 9)"), # the shell exits at the interrupt + ("trap '' INT; sleep 3; exit 4", 4, "(exit code 4)"), # the interrupt is ignored: it exits by itself + ], +) +def test_a_shell_that_ends_during_the_interrupt_is_reported_as_an_ended_session(tmp_path, command, code, named) -> None: + ns = "interrupt-ends" + ran = tmp_path / "ran" + try: + timed_out = _exec(command, ns, timeout=1, working_directory=str(tmp_path)) + assert timed_out["timed_out"] is True and timed_out["not_run"] is False + res = _exec("touch ran; echo NEVER_RUN", ns, timeout=10) + assert res["success"] is False and res["session_ended"] is True and res["return_code"] == code + assert res["not_run"] is True and not ran.exists() + # True whichever ended the shell (the interrupt, the shell itself): neither is claimed. + assert res["error"].startswith( + "The shell session ended while the previous command, which had timed out, was being interrupted " + named + ) + assert "this command was not run" in res["error"] and "the next call starts a new session" in res["error"] + assert "could not be resynchronised" not in res["rendered"] and "kept running" not in res["rendered"] + assert "NEVER_RUN" not in res["rendered"] + fresh = _exec("touch ran; echo fresh", ns, timeout=10, working_directory=str(tmp_path)) + assert fresh["success"] is True and "new shell session 'main' started" in fresh["rendered"] + assert fresh["not_run"] is False and ran.exists() + finally: + _close(ns) + + +def test_a_session_closed_from_another_thread_during_the_interrupt_is_an_ended_session(tmp_path) -> None: + from abstractcore.tools import shell_tools + from abstractcore.tools.shell_session import get_shell_session_registry, namespaced_session_id + + ns = "closed-meanwhile" + try: + assert _exec("true", ns, timeout=10, working_directory=str(tmp_path))["success"] is True + # The child ignores SIGINT, so the next call waits for a marker until the session is closed. + _start_child(get_shell_session_registry().get(namespaced_session_id(ns, "main")), _IGNORES_INTERRUPTS) + closer = threading.Timer(0.5, lambda: shell_tools.shell_close(_registry_namespace=ns)) + closer.start() + res = _exec("echo NEVER_RUN", ns, timeout=10) + closer.join() + assert res["success"] is False and res["session_ended"] is True and res["not_run"] is True + assert res["return_code"] is None and "NEVER_RUN" not in res["rendered"] + assert res["error"].startswith( + "The shell session ended while the previous command, which had timed out, was being interrupted " + "(exit code unknown); this command was not run" + ) + finally: + _close(ns) + + +def test_a_refused_interrupt_with_the_shell_still_there_is_stuck_not_ended(tmp_path, monkeypatch) -> None: + """The terminal takes no input but its output stream is still open: the shell is not known + to be gone, so the session is closed as one that could not be resynchronised.""" + from abstractcore.tools import shell_session + + monkeypatch.setattr(shell_session, "_RESYNC_ATTEMPT_TIMEOUT_S", 0.5) + reg = ShellSessionRegistry() + sess = reg.open(session_id="refused", cwd=str(tmp_path)) + try: + assert sess.run("sleep 100", timeout_s=1).timed_out is True + + def refused(data: str) -> None: + raise OSError(5, "Input/output error") + + monkeypatch.setattr(sess, "_write", refused) + with pytest.raises(RuntimeError, match="could not be resynchronised"): + sess.run("echo NEVER_RUN", timeout_s=5) + assert sess.is_alive() is False + finally: + reg.close_all() + + +def test_shell_write_stdin_does_not_teach_answering_a_first_prompt() -> None: + # A command's first prompt has already read shell_exec's status line as its answer: after + # that timeout a "y" is typed into the shell itself (the prompt test above shows it). + from abstractcore.tools import shell_tools + + td = shell_tools.shell_write_stdin._tool_definition + assert "a first prompt was already answered by shell_exec's status line" in td.when_to_use + assert "a later prompt" in td.description and "a later prompt of the same command" in td.when_to_use + assert [ex["description"] for ex in td.examples] == [ + "Evaluate in a REPL started earlier", + "Answer a later prompt of a command that is still running", + ] + for told in (td.description, td.when_to_use): + assert "confirmation prompt" not in told and "(REPL, prompt)" not in told + + +def test_a_shell_that_is_gone_when_the_interrupt_is_written_is_an_ended_session(tmp_path, monkeypatch) -> None: + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + try: + assert sess.run("exec sleep 100", timeout_s=1).timed_out is True + pid = sess._pid + + def refused(data: str) -> None: + os.kill(pid, signal.SIGKILL) # the shell dies, and its terminal takes no input + raise OSError(5, "Input/output error") + + monkeypatch.setattr(sess, "_write", refused) + r = sess.run("echo NEVER_RUN", timeout_s=10) + assert (r.session_ended, r.not_run, r.exit_code, r.stdout) == (True, True, -signal.SIGKILL, "") + assert sess.is_alive() is False + finally: + reg.close_all() + + +def test_the_end_of_the_stream_alone_says_the_shell_ended(tmp_path, monkeypatch) -> None: + """Where the terminal still takes input after its shell ended (the write does not fail), the + end of the output stream is the only sign: it is the shell ending, not one more deadline.""" + from abstractcore.tools import shell_session + + monkeypatch.setattr(shell_session, "_RESYNC_ATTEMPT_TIMEOUT_S", 0.5) + reg = ShellSessionRegistry() + sess = reg.open(cwd=str(tmp_path)) + try: + assert sess.run("exec sleep 100", timeout_s=1).timed_out is True + write = sess._write + + def never_refuses(data: str) -> None: + try: + write(data) + except OSError: + pass + + monkeypatch.setattr(sess, "_write", never_refuses) + r = sess.run("echo NEVER_RUN", timeout_s=10) + assert (r.session_ended, r.not_run, r.exit_code, r.stdout) == (True, True, -signal.SIGINT, "") + finally: + reg.close_all() + + +# --- Linux (2026-11-29): the interrupt of a timed-out command reaching an idle shell ---------- +# A reader waiting on the terminal when the Ctrl-C lands (the shell itself once the command has +# ended on its own, or its `read`) was handed the start of the sync line before it handled the +# interrupt and dropped it: bash ran `rintf …`, dash lost the line, on all three attempts, and +# the session was closed as "could not be resynchronised" with its state. macOS never showed it. + + +@pytest.mark.parametrize("shell_path", [None, "/bin/dash"], ids=["the default shell", "dash"]) +def test_a_command_that_ended_on_its_own_after_its_timeout_keeps_the_session(tmp_path, shell_path) -> None: + if shell_path and not os.access(shell_path, os.X_OK): + pytest.skip(f"no {shell_path} on this host") + reg = ShellSessionRegistry() + if shell_path: + sess = ShellSession(session_id="idle", shell_path=shell_path, cwd=str(tmp_path)) + sess.start() + else: + sess = reg.open(session_id="idle", cwd=str(tmp_path)) + try: + first = sess.run("KEPT=yes; sleep 2; echo ENDED_LATE", timeout_s=1) + assert first.timed_out is True + out = first.stdout + for _ in range(60): # a hang guard only: each read returns as soon as output arrives + if "__ABSTRACT_SENTINEL_" in out: + break # the status line has run: the command is over and the shell is idle + out += sess.read_output(timeout_s=2).stdout + else: + raise AssertionError(f"the command never ended: {out!r}") + assert "ENDED_LATE" in out + r = sess.run("echo after KEPT=$KEPT", timeout_s=10) + assert (r.stdout, r.exit_code, r.timed_out, r.session_ended) == ("after KEPT=yes\n", 0, False, False) + assert sess.run("echo again", timeout_s=10).stdout == "again\n" + finally: + sess.close() + reg.close_all() + + +def test_a_prompt_still_waiting_at_the_next_call_is_interrupted_and_the_session_kept(tmp_path) -> None: + ns = "waiting-prompt" + try: + # The first prompt reads the status line; the second is still waiting when the next call comes. + res = _exec("KEPT=yes; read -p 'first? ' a; read -p 'second? ' b; echo \"b=$b\"", ns, timeout=2, working_directory=str(tmp_path)) + assert res["timed_out"] is True and "second? " in res["rendered"] + after = _exec("echo after KEPT=$KEPT", ns, timeout=10) + assert after["success"] is True and after["rendered"] == "exit_code: 0\nafter KEPT=yes\n" + finally: + _close(ns)