Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions src/lecode/agent/tools/bash.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,18 @@ 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)
receives each chunk as it arrives; the retained buffer is then capped at
``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(),
Expand All @@ -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:
Expand All @@ -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):
Expand All @@ -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]:
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
6 changes: 4 additions & 2 deletions src/lecode/extras/background.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)}]"
Expand Down
18 changes: 15 additions & 3 deletions tests/test_tool_bash.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from __future__ import annotations

import asyncio
import contextlib
import os
import shlex
import stat
Expand Down Expand Up @@ -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
Loading