-
Notifications
You must be signed in to change notification settings - Fork 0
fix(agent): harden terminal execution and unblock cancelled approvals #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,74 +1,96 @@ | ||
| """Terminal command execution tool.""" | ||
|
|
||
| import os | ||
| import shlex | ||
| import subprocess | ||
|
|
||
| from langchain_core.tools import tool | ||
|
|
||
| from deep_code_agent.config import DEFAULT_TIMEOUT, MAX_TIMEOUT | ||
|
|
||
| DISALLOWED_SHELL_SYNTAX = ("&&", "||", "|", ";", "$(", "`", ">", "<", "\n", "\r") | ||
| DANGEROUS_COMMAND_SNIPPETS = ( | ||
| "rm -rf /", | ||
| "format", | ||
| "del /q", | ||
| "mkfs", | ||
| "shutdown", | ||
| "reboot", | ||
| "diskutil erasedisk", | ||
| ) | ||
|
|
||
|
|
||
| def _get_command_workdir() -> str: | ||
| """Resolve the agent-scoped working directory for terminal commands.""" | ||
| return os.environ.get("DEEP_CODE_AGENT_TERMINAL_CWD", os.getcwd()) | ||
|
|
||
|
|
||
| def _contains_disallowed_shell_syntax(command: str) -> bool: | ||
| """Reject shell-only syntax so commands can run without a shell.""" | ||
| return any(token in command for token in DISALLOWED_SHELL_SYNTAX) | ||
|
hzhaoy marked this conversation as resolved.
|
||
|
|
||
|
|
||
| @tool | ||
| def terminal(command: str, timeout: int = DEFAULT_TIMEOUT) -> str: | ||
| """Execute terminal commands with timeout protection. | ||
|
|
||
| Args: | ||
| command (str): Terminal command to execute. | ||
| timeout (int): Command timeout in seconds, defaults to 30. | ||
| command: Terminal command to execute. | ||
| timeout: Command timeout in seconds, defaults to 30. | ||
|
|
||
| Returns: | ||
| str: Command execution result. | ||
| Command execution result. | ||
| """ | ||
| # Validate timeout | ||
| if timeout <= 0: | ||
| return f"Error: Timeout must be positive, got {timeout}" | ||
| if timeout > MAX_TIMEOUT: | ||
| return f"Error: Timeout {timeout} exceeds maximum allowed {MAX_TIMEOUT} seconds" | ||
|
|
||
| if not command or not command.strip(): | ||
| return "Error: Command cannot be empty" | ||
|
|
||
| normalized_command = command.strip() | ||
| lower_command = normalized_command.lower() | ||
|
|
||
| for dangerous in DANGEROUS_COMMAND_SNIPPETS: | ||
| if dangerous in lower_command: | ||
| return f"Error: Command contains potentially dangerous operation: {dangerous}" | ||
|
|
||
| if _contains_disallowed_shell_syntax(normalized_command): | ||
| return "Error: Command contains disallowed shell control operators." | ||
|
|
||
| try: | ||
| # Validate command | ||
| if not command or not command.strip(): | ||
| return "Error: Command cannot be empty" | ||
| argv = shlex.split(normalized_command) | ||
| except ValueError as exc: | ||
| return f"Error: Invalid command syntax: {exc}" | ||
|
|
||
| # Security check - block dangerous commands | ||
| dangerous_commands = ["rm -rf /", "format", "del /q"] | ||
| for dangerous in dangerous_commands: | ||
| if dangerous in command.lower(): | ||
| return f"Error: Command contains potentially dangerous operation: {dangerous}" | ||
| if not argv: | ||
| return "Error: Command cannot be empty" | ||
|
|
||
| # Execute command | ||
| try: | ||
| result = subprocess.run( | ||
| command, | ||
| shell=True, | ||
| argv, | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=timeout, | ||
| cwd=os.getcwd(), | ||
| cwd=_get_command_workdir(), | ||
| ) | ||
|
|
||
| # Build output | ||
| output_parts = [] | ||
|
|
||
| if result.stdout: | ||
| output_parts.append(result.stdout) | ||
| if result.stderr: | ||
| output_parts.append(f"STDERR:\n{result.stderr}") | ||
|
|
||
| # Add status info | ||
| status_info = f"Command executed with exit code: {result.returncode}" | ||
| if result.returncode != 0: | ||
| status_info += " (non-zero exit code indicates potential error)" | ||
| output_parts.append(status_info) | ||
|
|
||
| return "\n".join(output_parts) if output_parts else "Command executed successfully with no output." | ||
| return "\n".join(output_parts) | ||
|
|
||
| except subprocess.TimeoutExpired: | ||
| return f"Error: Command timed out after {timeout} seconds." | ||
| except FileNotFoundError: | ||
| return "Error: Command shell not found. Please ensure shell is available." | ||
| except PermissionError: | ||
| return f"Error: Permission denied executing command '{command}'" | ||
| except OSError as e: | ||
| return f"Error: OS error executing command '{command}': {str(e)}" | ||
| except Exception as e: | ||
| return f"Error executing command '{command}': {str(e)}" | ||
| return "Error: Permission denied to execute command." | ||
| except Exception as exc: | ||
| return f"Error executing command: {exc}" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.