AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

ShellToolMiddleware Command Timeout Silently Resets Session And Skips Startup_commands

When a shell command times out, ShellSession.execute restarts the shell but ShellToolMiddleware does not re-run startup_commands. Any shell hardening (ulimit, umask, exported variables, readonly tokens) and working directory are silently lost, while the model is not informed that the session was reset.

highConfidence 95%LangchainAffected V1.2.9Affected V1.3.17

Origin Analysis

ShellSession.execute has a timeout branch that calls self.restart() internally, recreating the shell process. However, the corresponding timeout branch in ShellToolMiddleware._run_shell_tool only returns an error string and does not call self._run_startup_commands(session), unlike the explicit restart branch which does. This leaves the restarted session without the user-provided startup guards and returns no notice to the model.
Run the provided Python reproduction using ShellSession with HostExecutionPolicy(command_timeout=1.0). Execute startup commands: export TOKEN=secret; readonly TOKEN; ulimit -f 100; umask 0077; mkdir -p sub; cd sub. Then execute 'sleep 5' with timeout=1.0. Observe that after timeout, ulimit -f returns unlimited, umask returns 0002, TOKEN is unset, readonly protection is gone, and cwd is reset to workspace. The session still responds to commands.

Fixing Code Block

Edge Case Audit

Re-running startup commands after every timeout may cause side effects if those commands are not idempotent (e.g., appending to files, creating directories with mkdir -p is safe, but arbitrary user commands may allocate resources or duplicate actions). If startup_commands contain one-time setup or mutable state, repeated execution could lead to incorrect environment. Rollback suggestion: if this change causes unwanted duplicate side effects, replace the automatic re-run with only an explicit message and require users to set idempotent startup commands or provide a callback. Concurrency/threading: ShellSession is not documented as thread-safe; simultaneous tool calls against the same session could race between restart and startup re-run. Cross-platform: the fix relies on _run_startup_commands behaving identically across HostExecutionPolicy and DockerExecutionPolicy; test both. Also ensure _run_startup_commands itself respects timeouts to avoid hanging the tool.

Ecosystem Topology