Files
wehub-resource-sync 4b6817381b
CI (OpenClaw E2E) / openclaw test (push) Has been cancelled
CI / coverage-report (push) Has been cancelled
CI / test-kubernetes (push) Has been cancelled
CI / should-run-thorough (push) Has been cancelled
CI / test-thorough (cloudwatch-demo) (push) Has been cancelled
CI / test-thorough (flink-ecs) (push) Has been cancelled
CI / test-thorough (upstream-lambda) (push) Has been cancelled
CI / test-thorough (prefect-ecs-fargate) (push) Has been cancelled
Release / build-binaries (zip, opensre.exe, onefile, windows-latest, windows-x64) (push) Has been cancelled
Benchmark image — build + push to ECR (any adapter) / build + push (push) Has been cancelled
CI / quality (ubuntu-latest) (push) Has been cancelled
CI / test (tools-runtime) (push) Has been cancelled
CI / test (e2e-general) (push) Has been cancelled
CI / test (cli-runtime) (push) Has been cancelled
CI / test (e2e-provider-and-openclaw) (push) Has been cancelled
CI / test (integrations-and-misc) (push) Has been cancelled
Release / verify (push) Has been cancelled
Release / build-python-dist (push) Has been cancelled
Release / build-binaries (tar.gz, opensre, onedir, macos-15-intel, darwin-x64) (push) Has been cancelled
Release / build-binaries (tar.gz, opensre, onedir, macos-latest, darwin-arm64) (push) Has been cancelled
Release / build-binaries (tar.gz, opensre, onedir, ubuntu-22.04, linux-x64) (push) Has been cancelled
Release / publish-release (push) Has been cancelled
Release / publish-main-release (push) Has been cancelled
Interactive Shell Live (PR + post-merge) / turn-checks (no-LLM) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
Interactive Shell Live (PR + post-merge) / turn-live shard ${{ matrix.shard_index }} (push) Has been cancelled
Release / prepare (push) Has been cancelled
Release / build-binaries (tar.gz, opensre, onedir, ubuntu-22.04-arm, linux-arm64) (push) Has been cancelled
Synthetic Deterministic Tests / Synthetic offline (deterministic) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 13:10:45 +08:00

126 lines
3.6 KiB
Python

"""Structured shell command execution helpers for the interactive REPL."""
from __future__ import annotations
import os
import subprocess
from dataclasses import dataclass
@dataclass(frozen=True)
class ShellExecutionResult:
"""Normalized command execution output."""
command: str
argv: list[str] | None
stdout: str
stderr: str
exit_code: int | None
timed_out: bool
truncated: bool
executed_with_shell: bool
def _truncate_output(text: str, *, max_chars: int) -> tuple[str, bool]:
if len(text) <= max_chars:
return text, False
return f"{text[:max_chars].rstrip()}\n... output truncated ...", True
def _text_from_timeout_stream(raw: str | bytes | None) -> str:
if raw is None:
return ""
if isinstance(raw, str):
return raw
return raw.decode("utf-8", errors="replace")
def _shell_argv(command: str) -> list[str]:
if os.name == "nt":
shell = os.environ.get("COMSPEC") or "cmd.exe"
return [shell, "/d", "/s", "/c", command]
shell = os.environ.get("SHELL") or "/bin/sh"
return [shell, "-lc", command]
def execute_shell_command(
*,
command: str,
argv: list[str] | None,
use_shell: bool,
timeout_seconds: int,
max_output_chars: int,
) -> ShellExecutionResult:
"""Execute a command and return a structured result object."""
try:
if use_shell:
# Intentional REPL shell passthrough for local terminal commands.
# The caller runs through interactive confirmation/policy first and
# records that the command used a shell in ShellExecutionResult.
completed = subprocess.run(
_shell_argv(command),
shell=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout_seconds,
check=False,
)
else:
if argv is None:
raise ValueError("argv is required for shell=False execution.")
completed = subprocess.run(
argv,
shell=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout_seconds,
check=False,
)
except subprocess.TimeoutExpired as exc:
stdout = _text_from_timeout_stream(exc.stdout)
stderr = _text_from_timeout_stream(exc.stderr)
stdout, truncated_stdout = _truncate_output(
stdout,
max_chars=max_output_chars,
)
stderr, truncated_stderr = _truncate_output(
stderr,
max_chars=max_output_chars,
)
return ShellExecutionResult(
command=command,
argv=argv,
stdout=stdout,
stderr=stderr,
exit_code=None,
timed_out=True,
truncated=truncated_stdout or truncated_stderr,
executed_with_shell=use_shell,
)
stdout, truncated_stdout = _truncate_output(
completed.stdout or "",
max_chars=max_output_chars,
)
stderr, truncated_stderr = _truncate_output(
completed.stderr or "",
max_chars=max_output_chars,
)
return ShellExecutionResult(
command=command,
argv=argv,
stdout=stdout,
stderr=stderr,
exit_code=completed.returncode,
timed_out=False,
truncated=truncated_stdout or truncated_stderr,
executed_with_shell=use_shell,
)
__all__ = ["ShellExecutionResult", "execute_shell_command"]