diff --git a/src/lecode/agent/tools/bash.py b/src/lecode/agent/tools/bash.py index 7ff18d7..5688e2d 100644 --- a/src/lecode/agent/tools/bash.py +++ b/src/lecode/agent/tools/bash.py @@ -53,8 +53,8 @@ async def _run_shell( shell: str | None = None, on_chunk: Callable[[bytes], None] | None = None, proc_slot: dict[str, Any] | None = None, -) -> tuple[bytes, int, bool, bool]: - """Run a shell command; returns (output, exit_code, timed_out, idle_killed). +) -> tuple[bytes, int, bool, bool, bool]: + """Run a shell command; see the return tuple described below. ``shell`` overrides the executable; the default is the user's shell (:func:`lecode.extras.shell.user_shell`). ``on_chunk`` (background tasks) @@ -62,6 +62,9 @@ async def _run_shell( ``max_bytes`` (the tail), since the caller streams the full output elsewhere. ``proc_slot`` receives the spawned process under ``"proc"`` so the caller can signal it. + + Returns ``(output, exit_code, timed_out, idle_killed, interrupted)``; + on cancellation the partial output is returned instead of raising. """ proc = await asyncio.create_subprocess_exec( shell or user_shell(), @@ -78,7 +81,7 @@ async def _run_shell( buffer = bytearray() deadline = time.monotonic() + timeout idle_deadline = time.monotonic() + idle_timeout - timed_out = idle_killed = aborted = False + timed_out = idle_killed = aborted = interrupted = False try: while True: @@ -101,11 +104,14 @@ async def _run_shell( if len(buffer) > max_bytes: del buffer[: len(buffer) - max_bytes] idle_deadline = time.monotonic() + idle_timeout + except asyncio.CancelledError: + # User interrupt: keep whatever was printed so far (partial result). + interrupted = True except BaseException: aborted = True raise finally: - if aborted or timed_out or idle_killed: + if aborted or interrupted or timed_out or idle_killed: _kill_tree(proc) with contextlib.suppress(TimeoutError, asyncio.CancelledError): async with asyncio.timeout(5.0): @@ -118,10 +124,10 @@ async def _run_shell( pass await proc.wait() - with contextlib.suppress(TimeoutError): + with contextlib.suppress(TimeoutError, asyncio.CancelledError): await asyncio.wait_for(proc.wait(), timeout=5.0) exit_code = proc.returncode if proc.returncode is not None else -1 - return bytes(buffer), exit_code, timed_out, idle_killed + return bytes(buffer), exit_code, timed_out, idle_killed, interrupted def _save_overflow(output: BinaryIO) -> tuple[Path, str, str]: @@ -209,7 +215,7 @@ async def run(self, args: dict, ctx: ToolContext) -> ToolResult: return ToolResult(f"background task {record.id} started: {command}") try: with tempfile.SpooledTemporaryFile(max_size=MAX_OUTPUT_BYTES) as output: - _, exit_code, timed_out, idle_killed = await _run_shell( + _, exit_code, timed_out, idle_killed, interrupted = await _run_shell( command, ctx.cwd, timeout, @@ -233,16 +239,18 @@ async def run(self, args: dict, ctx: ToolContext) -> ToolResult: return ToolResult(f"error: {e}", is_error=True) notes: list[str] = [] + if interrupted: + notes.append("interrupted, partial output") if timed_out: notes.append(f"timed out after {timeout}s") if idle_killed: notes.append(f"killed: no output for {idle}s") - if exit_code != 0: + if exit_code != 0 and not interrupted: notes.append(f"exit code {exit_code}") suffix = f"\n[{'; '.join(notes)}]" if notes else "" return ToolResult( (text.rstrip("\n") or "(no output)") + suffix, - is_error=timed_out or idle_killed or exit_code != 0, + is_error=interrupted or timed_out or idle_killed or exit_code != 0, metadata={ "proc_result": ProcResult( exit_code=exit_code, diff --git a/src/lecode/extras/background.py b/src/lecode/extras/background.py index d24a9d7..5fb47bf 100644 --- a/src/lecode/extras/background.py +++ b/src/lecode/extras/background.py @@ -310,7 +310,7 @@ def start_shell_task( proc_slot: dict[str, Any] = {} async def body(emit: Emit) -> tuple[str, int | None]: - output, exit_code, timed_out, idle_killed = await _run_shell( + output, exit_code, timed_out, idle_killed, interrupted = await _run_shell( command, cwd, timeout, @@ -321,11 +321,13 @@ async def body(emit: Emit) -> tuple[str, int | None]: ) text = output.decode("utf-8", errors="replace").rstrip("\n") or "(no output)" notes: list[str] = [] + if interrupted: + notes.append("interrupted, partial output") if timed_out: notes.append(f"timed out after {timeout}s") if idle_killed: notes.append(f"killed: no output for {idle_timeout}s") - if exit_code != 0 and not (timed_out or idle_killed): + if exit_code != 0 and not (timed_out or idle_killed or interrupted): notes.append(f"exit code {exit_code}") if notes: text += f"\n[{'; '.join(notes)}]" diff --git a/tests/test_tool_bash.py b/tests/test_tool_bash.py index f25e8d5..1138532 100644 --- a/tests/test_tool_bash.py +++ b/tests/test_tool_bash.py @@ -3,7 +3,6 @@ from __future__ import annotations import asyncio -import contextlib import os import shlex import stat @@ -196,11 +195,24 @@ async def test_cancel_kills_child(tool_ctx): task = asyncio.ensure_future(tool.run({"command": "sleep 30"}, tool_ctx)) await asyncio.sleep(0.2) task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await task + result = await task + assert result.is_error + assert "interrupted, partial output" in result.content out = subprocess.run(["pgrep", "-f", "sleep 30"], capture_output=True).stdout assert out == b"", subprocess.run( ["ps", "-p", ",".join(out.decode().split()), "-o", "pid,ppid,pgid,state,command"], capture_output=True, text=True, ).stdout + + +async def test_cancel_keeps_partial_output(tool_ctx): + """Interrupting a command keeps what it printed, marked as partial.""" + tool = bash.make_tool() + task = asyncio.ensure_future(tool.run({"command": "echo part1; sleep 30"}, tool_ctx)) + await asyncio.sleep(0.5) + task.cancel() + result = await task + assert result.is_error + assert "part1" in result.content + assert "interrupted, partial output" in result.content