💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Fix bash tool hanging on commands that read stdin (#1210)
Paco Cartones876cd07cf7b8
diff --git a/src/python/txtai/agent/tool/bash.py b/src/python/txtai/agent/tool/bash.pyindex deda1cea..30acdc52 100644--- a/src/python/txtai/agent/tool/bash.py+++ b/src/python/txtai/agent/tool/bash.py@@ -14,12 +14,13 @@ class BashTool(Tool):"""# pylint: disable=W0231- def __init__(self, allowed=None):+ def __init__(self, allowed=None, timeout=30):"""Creates a BashTool.Args:allowed: list of allowed commands to run, has limited set of defaults which are a best effort not a sandbox+ timeout: maximum number of seconds to wait for a command to complete, defaults to 30, None disables the timeout"""# Tool parameters@@ -33,6 +34,9 @@ class BashTool(Tool):# Default list of allowed commandsself.allowed = allowed if allowed else ["cat", "cut", "diff", "grep", "head", "ls", "tail"]+ # Maximum time to wait for a command, None waits indefinitely+ self.timeout = timeout+# Validate parameters and initialize toolsuper().__init__()@@ -41,6 +45,9 @@ class BashTool(Tool):"""Runs a shell command as a subprocess.+ stdin is closed and a timeout is applied. Otherwise an allowed command called with no file arguments+ (i.e. `cat`) reads from stdin and blocks the agent indefinitely.+Args:command: command arguments as a list@@ -50,6 +57,9 @@ class BashTool(Tool):output = Noneif command and command[0] in self.allowed:- output = subprocess.run(command, capture_output=True, text=True, check=False).stdout+ try:+ output = subprocess.run(command, capture_output=True, text=True, check=False, stdin=subprocess.DEVNULL, timeout=self.timeout).stdout+ except subprocess.TimeoutExpired:+ output = f"Command timed out after {self.timeout} seconds"return outputdiff --git a/test/python/testagent.py b/test/python/testagent.pyindex d211db08..986c08a9 100644--- a/test/python/testagent.py+++ b/test/python/testagent.py@@ -6,6 +6,7 @@ import osimport tempfileimport unittest+from threading import Threadfrom unittest.mock import patchfrom datetime import datetime@@ -13,7 +14,7 @@ from datetime import datetimefrom smolagents import CodeAgent, PythonInterpreterToolfrom txtai.agent import Agent-from txtai.agent.tool import ToolFactory+from txtai.agent.tool import BashTool, ToolFactoryfrom txtai.embeddings import Embeddings# agents.md content@@ -189,6 +190,48 @@ class TestAgent(unittest.TestCase):self.assertEqual(tool.name, "bash")self.assertIsNot(tool, ToolFactory.default("bash"))+ def testToolsBashStdin(self):+ """+ Test default bash tool doesn't block reading stdin+ """++ tool = ToolFactory.default("bash")++ # Replace stdin with a pipe that never reaches EOF, simulating a long-lived+ # parent process (i.e. an API service) that keeps stdin open+ read, write = os.pipe()+ stdin = os.dup(0)++ result = {}++ try:+ os.dup2(read, 0)++ # `cat` with no file arguments reads stdin - run in a thread to avoid blocking the test suite+ thread = Thread(target=lambda: result.update(output=tool(["cat"])), daemon=True)+ thread.start()+ thread.join(timeout=30)+ finally:+ os.dup2(stdin, 0)+ for descriptor in (stdin, read, write):+ os.close(descriptor)++ # Command must return and not block forever reading stdin+ self.assertFalse(thread.is_alive())+ self.assertEqual(result["output"], "")++ def testToolsBashTimeout(self):+ """+ Test bash tool commands are stopped once they exceed the timeout+ """++ tool = BashTool(allowed=["sleep"], timeout=1)++ self.assertIn("timed out", tool(["sleep", "30"]))++ # Timeout is disabled when set to None+ self.assertIsNone(BashTool(timeout=None).timeout)+def testToolsEmbeddings(self):"""Test adding Embeddings as a tool