[Bug] CAI hangs when running interactive tools (radare2, gdb, python) due to blocking os.read()
Description
I encountered an issue where CAI freezes indefinitely when executing interactive tools such as radare2, gdb, or python REPL. The session becomes unresponsive because the tool waits for user input while the CAI reader loop blocks waiting for output.
Root Cause Analysis
-
Location:
src/cai/tools/common.py(approx. line 268) -
Method:
ShellSession._read_output()
The issue stems from a blocking os.read() call without a timeout. When an interactive program produces no output (e.g., waiting for input), os.read() blocks execution indefinitely, causing the entire session to hang.
Problematic Code
# Current implementation blocks forever if no data is available
output = os.read(self.master, 4096)
Proposed Fix To resolve this, we should use select.select() to check if data is available before attempting to read. This implements a non-blocking read mechanism with a timeout.
import select
# ... inside ShellSession._read_output ...
# Check if data is ready to be read with a 0.5s timeout
ready, _, _ = select.select([self.master], [], [], 0.5)
if ready:
output = os.read(self.master, 4096)
else:
# Handle timeout or empty buffer appropriately
pass
- Additional Recommendations
- Session Timeout: Add a CAI_SESSION_IDLE_TIMEOUT environment variable to auto-terminate stuck sessions (default: 300s)
@aliasrobotics-support and @luijait any chance to have a look at this please?
will look into it.
@slonce70 please note that your fix has been taken into consideration and added in PR #370
Please keep track of this contribution to see if the mentioned issue has been addressed.
Thank you for your contribution
@slonce70 this has been approved on our side.
You can directly downloaded or stay tuned for the pip release that will be announced in https://discord.com/channels/1359128560526168224/1359128560991863011 anytime soon.