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
23 changes: 14 additions & 9 deletions openhands-agent-server/openhands/agent_server/bash_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,16 +187,16 @@ def _signal_process_group(
self,
process: asyncio.subprocess.Process,
sig: signal.Signals,
command: str,
) -> None:
try:
os.killpg(os.getpgid(process.pid), sig)
except ProcessLookupError:
pass
except OSError as e:
logger.debug(
f"Failed to send {sig.name} to process group for command "
f"'{command}': {e}"
"Failed to send %s to process group (error_type=%s)",
sig.name,
type(e).__name__,
)

async def start_bash_command(
Expand Down Expand Up @@ -298,21 +298,22 @@ async def read_stream(stream, is_stderr=False):
except TimeoutError:
# Send SIGTERM to the whole process group so user-installed
# cleanup traps can run, then escalate to SIGKILL if needed.
self._signal_process_group(process, signal.SIGTERM, command.command)
self._signal_process_group(process, signal.SIGTERM)
try:
await asyncio.wait_for(process.wait(), timeout=1.0)
except TimeoutError:
self._signal_process_group(process, signal.SIGKILL, command.command)
self._signal_process_group(process, signal.SIGKILL)
try:
await asyncio.wait_for(process.wait(), timeout=1.0)
except TimeoutError:
logger.error(
f"Failed to kill process for command: {command.command}"
"Failed to kill process (command_id=%s)", command.id
)
exit_code = -1
logger.warning(
f"Command timed out after {command.timeout} seconds: "
f"{command.command}"
"Command timed out after %s seconds (command_id=%s)",
command.timeout,
command.id,
)

# Create final output event with any remaining buffer content and exit code
Expand All @@ -334,7 +335,11 @@ async def read_stream(stream, is_stderr=False):
await self._pub_sub(final_output)

except Exception as e:
logger.error(f"Error executing bash command '{command.command}': {e}")
logger.error(
"Error executing bash command (command_id=%s, error_type=%s)",
command.id,
type(e).__name__,
)
# Create error output event
error_output = BashOutput(
command_id=command.id,
Expand Down
65 changes: 44 additions & 21 deletions openhands-agent-server/openhands/agent_server/sockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
from openhands.agent_server.models import (
BashError,
BashEventBase,
BashOutput,
ExecuteBashRequest,
ServerErrorEvent,
)
Expand Down Expand Up @@ -445,31 +446,32 @@ async def bash_events_socket(
try:
# Keep the connection alive and handle any incoming messages
data = await websocket.receive_json()
if _is_auth_control_message(data):
continue
logger.info("Received bash request")
request = ExecuteBashRequest.model_validate(data)
await bash_service.start_bash_command(request)
except WebSocketDisconnect:
logger.info("Bash websocket disconnected")
return
except Exception as e:
# Something went wrong - Tell the client so they can handle it
try:
error_event = BashError(
code=e.__class__.__name__,
detail=str(e),
)
dumped = error_event.model_dump(mode="json")
await websocket.send_json(dumped)
# Log after - if send event raises an error logging is handled
# in the except block
logger.exception(
"error_in_bash_event_subscription", stack_info=True
logger.error(
"error_in_bash_event_subscription (error_type=%s)",
type(e).__name__,
)
except Exception:
# Sending the error event failed - likely a closed socket
logger.info("Base websocket disconnected")
except Exception as send_error:
logger.info("Bash websocket disconnected")
logger.debug(
"error_sending_bash_error", exc_info=True, stack_info=True
"error_sending_bash_error (error_type=%s, send_error_type=%s)",
type(e).__name__,
type(send_error).__name__,
)
await _safe_close_websocket(websocket)
return
Expand All @@ -493,14 +495,12 @@ async def _send_event(event: Event, websocket: WebSocket):


def _is_auth_control_message(data: object) -> bool:
"""Return True for ``{"type": "auth", ...}`` first-message-auth frames.

Clients that handle both legacy and first-message auth may send this
frame even after legacy (query/header) auth has already succeeded.
The post-auth receive loops must ignore it instead of validating it
as a regular message payload.
"""
return isinstance(data, dict) and data.get("type") == "auth"
"""Match redundant auth frames left unread after legacy authentication."""
return (
isinstance(data, dict)
and data.get("type") == "auth"
and set(data) <= {"type", "session_api_key"}
)


async def _safe_close_websocket(
Expand Down Expand Up @@ -546,16 +546,39 @@ async def __call__(self, event: Event):


async def _send_bash_event(event: BashEventBase, websocket: WebSocket):
metadata: dict[str, str | int | None] = {
"kind": event.kind,
"event_id": str(event.id),
"command_id": None,
"order": None,
"exit_code": None,
}
if isinstance(event, BashOutput):
metadata.update(
command_id=str(event.command_id),
order=event.order,
exit_code=event.exit_code,
)

if not _is_websocket_connected(websocket):
logger.debug("skip_sending_bash_event_socket_disconnected: %r", event)
logger.debug("skip_sending_bash_event_socket_disconnected: %s", metadata)
return
try:
dumped = event.model_dump(mode="json")
await websocket.send_json(dumped)
except (RuntimeError, WebSocketDisconnect) as e:
logger.debug("error_sending_bash_event_disconnected: %r (%s)", event, e)
except Exception:
logger.exception("error_sending_bash_event: %r", event, stack_info=True)
logger.debug(
"error_sending_bash_event_disconnected: %s (error_type=%s)",
metadata,
type(e).__name__,
)
except Exception as e:
logger.error(
"error_sending_bash_event: %s (error_type=%s)",
metadata,
type(e).__name__,
stack_info=True,
)


@dataclass
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def _execute_command_generator(
Returns:
CommandResult: Result with stdout, stderr, exit_code, and other metadata
"""
_logger.debug(f"Executing remote command: {command}")
_logger.debug("Executing remote command")

# Step 1: Start the bash command
payload = {
Expand Down Expand Up @@ -173,7 +173,11 @@ def _execute_command_generator(

# If we timed out waiting for completion
if exit_code is None:
_logger.warning(f"Command timed out after {timeout} seconds: {command}")
_logger.warning(
"Command timed out after %s seconds (command_id=%s)",
timeout,
command_id,
)
exit_code = -1
stderr_parts.append(f"Command timed out after {timeout} seconds")

Expand All @@ -190,7 +194,10 @@ def _execute_command_generator(
)

except Exception as e:
_logger.error(f"Remote command execution failed: {e}")
_logger.error(
"Remote command execution failed (error_type=%s)",
type(e).__name__,
)
return CommandResult(
command=command,
exit_code=-1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def _write_pty(self, data: bytes) -> None:
if self._pty_master_fd is None:
raise RuntimeError("PTY terminal is not initialized")
try:
logger.debug(f"Wrote to subprocess PTY: {data!r}")
logger.debug("Wrote to subprocess PTY (byte_count=%s)", len(data))
os.write(self._pty_master_fd, data)
except Exception as e:
logger.error(f"Failed to write to PTY: {e}", exc_info=True)
Expand Down Expand Up @@ -465,7 +465,7 @@ def read_screen(self) -> str:
content = "".join(self.output_buffer)
lines = content.split("\n")
content = "\n".join(lines).replace("\r", "")
logger.debug(f"Read from subprocess PTY: {content!r}")
logger.debug("Read from subprocess PTY (content_length=%s)", len(content))
return content

def clear_screen(self) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,9 @@ def _handle_completed_command(
self._cwd: str = metadata.working_dir

logger.debug(
f"[Prev PS1 not matched: {get_content_before_last_match}] "
f"COMMAND OUTPUT: {terminal_content}"
"Parsed terminal output (previous_ps1_not_matched=%s, content_length=%s)",
get_content_before_last_match,
len(terminal_content),
)
# Extract the command output between the two PS1 prompts
raw_command_output = self._combine_outputs_between_matches(
Expand Down Expand Up @@ -300,9 +301,10 @@ def _handle_nochange_timeout_command(
self.prev_status = TerminalCommandStatus.NO_CHANGE_TIMEOUT
if len(ps1_matches) != 1:
logger.warning(
f"Expected exactly one PS1 metadata block BEFORE the execution of a "
f"command, but got {len(ps1_matches)} PS1 metadata blocks:\n"
f"---\n{terminal_content!r}\n---"
"Expected exactly one PS1 metadata block before command execution, "
"but got %s (content_length=%s)",
len(ps1_matches),
len(terminal_content),
)
raw_command_output = self._combine_outputs_between_matches(
terminal_content, ps1_matches
Expand Down Expand Up @@ -339,9 +341,10 @@ def _handle_hard_timeout_command(
self.prev_status = TerminalCommandStatus.HARD_TIMEOUT
if len(ps1_matches) != 1:
logger.warning(
f"Expected exactly one PS1 metadata block BEFORE the execution of a "
f"command, but got {len(ps1_matches)} PS1 metadata blocks:\n"
f"---\n{terminal_content!r}\n---"
"Expected exactly one PS1 metadata block before command execution, "
Comment thread
simonrosenberg marked this conversation as resolved.
Resolved
"but got %s (content_length=%s)",
len(ps1_matches),
len(terminal_content),
)
raw_command_output = self._combine_outputs_between_matches(
terminal_content, ps1_matches
Expand Down Expand Up @@ -397,7 +400,9 @@ def _combine_outputs_between_matches(
combined_output += output_segment + "\n"
# Add the content after the last PS1 prompt
combined_output += terminal_content[ps1_matches[-1].end() + 1 :]
logger.debug(f"COMBINED OUTPUT: {combined_output}")
logger.debug(
"Combined terminal output (content_length=%s)", len(combined_output)
)
return combined_output

def execute(self, action: TerminalAction) -> TerminalObservation:
Expand All @@ -406,7 +411,11 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
raise RuntimeError("Unified session is not initialized")

# Strip the command of any leading/trailing whitespace
logger.debug(f"RECEIVED ACTION: {action}")
logger.debug(
"Received terminal action (is_input=%s, command_length=%s)",
action.is_input,
len(action.command),
)
command = action.command.strip()
is_input: bool = action.is_input

Expand Down Expand Up @@ -465,7 +474,10 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
)
initial_ps1_count = len(initial_ps1_matches)
logger.debug(f"Initial PS1 count: {initial_ps1_count}")
logger.debug(f"INITIAL TERMINAL OUTPUT: {initial_terminal_output!r}")
logger.debug(
"Initial terminal output (content_length=%s)",
len(initial_terminal_output),
)

start_time = time.time()
last_change_time = start_time
Expand Down Expand Up @@ -499,7 +511,10 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
f"command is completed. By setting `is_input` to `true`, you can "
f"interact with the current process: {TIMEOUT_MESSAGE_TEMPLATE}]"
)
logger.debug(f"PREVIOUS COMMAND OUTPUT: {raw_command_output}")
logger.debug(
"Previous command output (content_length=%s)",
len(raw_command_output),
)
command_output = self._get_command_output(
command,
raw_command_output,
Expand All @@ -516,15 +531,16 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
exit_code=metadata.exit_code,
is_error=True,
)
logger.debug(f"RETURNING OBSERVATION (previous-command): {obs}")
return obs

# Send actual command/inputs to the terminal
sent_command = command != ""
if command != "":
is_special_key = self._is_special_key(command)
if is_input:
logger.debug(f"SENDING INPUT TO RUNNING PROCESS: {command!r}")
logger.debug(
"Sending input to running process (input_length=%s)", len(command)
)
self.terminal.send_keys(
command,
enter=not is_special_key,
Expand All @@ -534,7 +550,7 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
if not self.terminal.is_powershell():
# Only escape for bash terminals, not PowerShell
command = escape_bash_special_chars(command)
logger.debug(f"SENDING COMMAND: {command!r}")
logger.debug("Sending command (command_length=%s)", len(command))
Comment thread
simonrosenberg marked this conversation as resolved.
Resolved
self.terminal.send_keys(
command,
enter=not is_special_key,
Expand All @@ -549,10 +565,7 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
f"TERMINAL CONTENT GOT after {time.time() - _start_time:.2f} seconds"
)
logger.debug(
f"BEGIN OF TERMINAL CONTENT: {cur_terminal_output.split('\n')[:10]}"
)
logger.debug(
f"END OF TERMINAL CONTENT: {cur_terminal_output.split('\n')[-10:]}"
"Terminal content read (content_length=%s)", len(cur_terminal_output)
)
ps1_matches = CmdOutputMetadata.matches_ps1_metadata(cur_terminal_output)
current_ps1_count = len(ps1_matches)
Expand All @@ -579,7 +592,6 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
terminal_content=cur_terminal_output,
ps1_matches=ps1_matches,
)
logger.debug(f"RETURNING OBSERVATION (completed): {obs}")
return obs

# Timeout checks should only trigger if a new prompt hasn't appeared yet.
Expand All @@ -603,7 +615,6 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
terminal_content=cur_terminal_output,
ps1_matches=ps1_matches,
)
logger.debug(f"RETURNING OBSERVATION (nochange-timeout): {obs}")
return obs

# 3) Execution timed out since the command has been running for too long
Expand All @@ -621,7 +632,6 @@ def execute(self, action: TerminalAction) -> TerminalObservation:
ps1_matches=ps1_matches,
timeout=action.timeout,
)
logger.debug(f"RETURNING OBSERVATION (hard-timeout): {obs}")
return obs

# Sleep before next check
Expand Down
Loading
Loading