import asyncio async def shell_executor(command: str, timeout: int = 30) -> str: """在服务器上执行 shell 命令并返回输出。 Args: command: 要执行的 shell 命令 timeout: 超时秒数,默认 30 秒 Returns: 命令的 stdout + stderr 输出 """ from kilostar.utils.sandbox import ( validate_shell_command, CommandViolation, get_shell_timeout, ) try: command = validate_shell_command(command) except CommandViolation as e: return f"[Sandbox] {e}" timeout = get_shell_timeout(timeout) try: proc = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await asyncio.wait_for( proc.communicate(), timeout=timeout ) output = stdout.decode("utf-8", errors="replace") err_output = stderr.decode("utf-8", errors="replace") result = "" if output: result += output if err_output: result += f"\n[stderr]\n{err_output}" if proc.returncode != 0: result += f"\n[exit code: {proc.returncode}]" return result.strip() or "(no output)" except asyncio.TimeoutError: return f"[Error] 命令执行超时({timeout}s)" except Exception as e: return f"[Error] 执行失败: {e}"