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
83 changes: 83 additions & 0 deletions abstractcore/tools/command_verdict.py
Original file line number Diff line number Diff line change
@@ -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
157 changes: 121 additions & 36 deletions abstractcore/tools/common_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
Expand Down Expand Up @@ -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:
Expand All @@ -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 {}

Expand Down Expand Up @@ -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 ""
Expand All @@ -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,
Expand All @@ -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,
}
Expand Down Expand Up @@ -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,
}
Expand Down
Loading
Loading