fix(shell): separate wait, idle, and runtime limits (#6228)

* fix(shell): separate wait, idle, and runtime limits

* fix(shell): separate wait, idle, and runtime limits

* fix(exec): preserve settings aliases and reclaim completed sessions

* fix(webui): make shell runtime limits explicit
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-16 13:44:15 +08:00
1 parent 70ac000ad9
commit 6310a39bac
36 files changed
+2392 -564

No files matched your search

+339 -166
View File
@@ -10,7 +10,7 @@ import uuid
from collections import deque
from contextlib import suppress
from dataclasses import dataclass
from typing import Any
from typing import Any, Literal
from loguru import logger
@@ -36,7 +36,11 @@ DEFAULT_UNTIL_EXIT_MS = 600_000
MAX_WAIT_FOR_MS = 600_000
DEFAULT_MAX_OUTPUT_CHARS = 10_000
MAX_OUTPUT_CHARS = 50_000
OUTPUT_DRAIN_GRACE_S = 0.1
FinishReason = Literal[
"exit", "max_runtime", "idle_timeout", "cancelled", "owner_closed", "shutdown", "execution_error",
]
@dataclass(slots=True)
@@ -45,10 +49,27 @@ class _SessionPoll:
done: bool
exit_code: int | None
elapsed_s: float = 0.0
timed_out: bool = False
terminated: bool = False
finish_reason: FinishReason | None = None
stopping: bool = False
output_idle_s: float = 0.0
idle_timeout: int = 0
remaining_s: float | None = None
stdin_closed: bool = False
truncated_chars: int = 0
output_incomplete: bool = False
execution_error: str | None = None
@property
def failed(self) -> bool:
return self.timed_out or self.finish_reason == "execution_error"
@property
def timed_out(self) -> bool:
return self.finish_reason in ("max_runtime", "idle_timeout")
@property
def terminated(self) -> bool:
return self.finish_reason in ("cancelled", "owner_closed", "shutdown")
@dataclass(slots=True)
@@ -58,9 +79,13 @@ class ExecSessionInfo:
cwd: str
elapsed_s: float
idle_s: float
remaining_s: float
remaining_s: float | None
returncode: int | None
owner_session_key: str | None = None
idle_timeout: int = 0
stopping: bool = False
finish_reason: FinishReason | None = None
cleanup_error: str | None = None
class _BoundedOutputBuffer:
@@ -134,6 +159,9 @@ class _ExecSession:
timeout: int | None,
owner_session_key: str | None = None,
process_tree: bool = False,
idle_timeout: int = 300,
idle_action: Literal["report", "terminate"] = "report",
started_at: float | None = None,
) -> None:
self.session_id = session_id
self.process = process
@@ -141,32 +169,114 @@ class _ExecSession:
self.cwd = cwd
self.owner_session_key = owner_session_key
self._process_tree = process_tree
self.started_at = time.monotonic()
# timeout None/0 means no limit; an infinite deadline is never reached.
self.deadline = time.monotonic() + timeout if timeout else float("inf")
self.last_access = time.monotonic()
self.started_at = time.monotonic() if started_at is None else started_at
self.deadline = self.started_at + timeout if timeout else float("inf")
self.last_output_at: float | None = None
self.finished_at: float | None = None
self._execution_exited = False
self.idle_timeout = idle_timeout
self.idle_action = idle_action
self.finish_reason: FinishReason | None = None
self._stop_reason: FinishReason | None = None
self.cleanup_error: str | None = None
self._stop_complete = asyncio.Event()
self._state_changed = asyncio.Event()
self._output_incomplete = False
self._execution_error: str | None = None
self._stdout = _BoundedOutputBuffer(MAX_OUTPUT_CHARS)
self._stderr = _BoundedOutputBuffer(MAX_OUTPUT_CHARS)
self._lock = asyncio.Lock()
self._timed_out = False
self._kill_task: asyncio.Task[None] | None = None
self._stdout_task = asyncio.create_task(self._read_stream(process.stdout, self._stdout))
self._stderr_task = asyncio.create_task(self._read_stream(process.stderr, self._stderr))
self._timeout_task = asyncio.create_task(self._watch_timeout()) if timeout else None
self._completion_task = asyncio.create_task(self._complete())
self._completion_task.add_done_callback(self._on_supervisor_done)
self._timeout_task = (
asyncio.create_task(self._watch_timeout())
if timeout or (idle_timeout and idle_action == "terminate") else None
)
if self._timeout_task is not None:
self._timeout_task.add_done_callback(self._on_supervisor_done)
@property
def stopping(self) -> bool:
return self._stop_reason is not None and self.finished_at is None
def output_idle_s(self, now: float) -> float:
anchor = self.started_at if self.last_output_at is None else self.last_output_at
return max(0.0, now - anchor)
def remaining_s(self, now: float) -> float | None:
return max(0.0, self.deadline - now) if self.deadline != float("inf") else None
def _on_supervisor_done(self, task: asyncio.Task[None]) -> None:
if not task.cancelled() and (error := task.exception()) is not None:
if task is self._completion_task:
self.cleanup_error = str(error)
self._state_changed.set()
logger.opt(exception=error if tool_log_content_allowed() else False).error(
"Exec session supervision failed for {}", self.session_id,
)
async def _complete(self) -> None:
await self.process.wait()
# Root exit is not completion while a worker still holds captured pipes.
readers = asyncio.gather(self._stdout_task, self._stderr_task)
stopped = asyncio.create_task(self._stop_complete.wait())
try:
await asyncio.wait({readers, stopped}, return_when=asyncio.FIRST_COMPLETED)
if stopped.done():
try:
await asyncio.wait_for(readers, timeout=2.0)
except asyncio.TimeoutError:
self._output_incomplete = True
else:
await readers
self._execution_exited = True
if self._stop_reason is not None:
await stopped
finally:
stopped.cancel()
await asyncio.gather(stopped, return_exceptions=True)
from nanobot.agent.tools.shell import ExecTool, _reap_pid # pyright: ignore[reportPrivateUsage]
ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
_reap_pid(self.process.pid)
self.finish_reason = self._stop_reason or "exit"
self.finished_at = time.monotonic()
self._state_changed.set()
async def wait_exit(self) -> None:
while self.finished_at is None:
if self.cleanup_error is not None:
raise RuntimeError(f"session {self.session_id} cleanup failed: {self.cleanup_error}")
self._state_changed.clear()
await self._state_changed.wait()
async def _watch_timeout(self) -> None:
"""Enforce the hard deadline even when nobody polls this session."""
try:
await asyncio.wait_for(
self.process.wait(), timeout=max(0.0, self.deadline - time.monotonic()),
"""Supervise execution budgets independently of tool waits and log reads."""
while not self._completion_task.done():
now = time.monotonic()
deadline = self.deadline
if self.idle_timeout and self.idle_action == "terminate":
anchor = self.started_at if self.last_output_at is None else self.last_output_at
deadline = min(deadline, anchor + self.idle_timeout)
done, _ = await asyncio.wait(
{self._completion_task}, timeout=max(0.0, deadline - now),
)
except asyncio.TimeoutError:
if self.process.returncode is None:
if self._kill_task is None:
self._timed_out = True
# The kill callback logs failures; leave the session available for retry.
with suppress(Exception):
await self.kill()
if done:
return
if self._execution_exited:
await asyncio.shield(self._completion_task)
return
now = time.monotonic()
if now >= self.deadline:
await self.kill("max_runtime")
return
if self.idle_timeout and self.idle_action == "terminate":
if self.output_idle_s(now) >= self.idle_timeout:
await self.kill("idle_timeout")
return
async def _read_stream(
self,
@@ -177,13 +287,20 @@ class _ExecSession:
return
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
output_filter = ShellOutputFilter()
while True:
chunk = await stream.read(4096)
text = output_filter.feed(decoder.decode(chunk, final=not chunk))
async with self._lock:
buffer.append(text)
if not chunk:
break
try:
while True:
chunk = await stream.read(4096)
if chunk:
self.last_output_at = time.monotonic()
text = output_filter.feed(decoder.decode(chunk, final=not chunk))
async with self._lock:
buffer.append(text)
if not chunk:
break
except Exception as exc:
self._output_incomplete = True
self._execution_error = str(exc)
await self._begin_stop("execution_error")
async def write(self, chars: str) -> str | None:
if self.process.returncode is not None:
@@ -212,45 +329,16 @@ class _ExecSession:
yield_time_ms: int,
max_output_chars: int,
*,
terminated: bool = False,
stdin_closed: bool = False,
) -> _SessionPoll:
self.last_access = time.monotonic()
if yield_time_ms > 0 and self.process.returncode is None:
wait_s = min(yield_time_ms, MAX_YIELD_MS) / 1000
remaining_s = self.deadline - time.monotonic()
if remaining_s <= 0:
wait_s = 0
else:
wait_s = min(wait_s, remaining_s)
if wait_s > 0:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.process.wait(), timeout=wait_s)
if self.process.returncode is None and time.monotonic() >= self.deadline:
if self._kill_task is None:
self._timed_out = True
await self.kill()
if self._kill_task is not None:
# Finish termination before releasing process-tree ownership or returning output.
await asyncio.shield(self._kill_task)
if self.process.returncode is not None:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(
asyncio.gather(self._stdout_task, self._stderr_task),
timeout=2.0,
)
# Safety-net reap after normal exit.
from nanobot.agent.tools.shell import ( # pyright: ignore[reportPrivateUsage]
ExecTool,
_reap_pid, # pyright: ignore[reportPrivateUsage]
if yield_time_ms > 0 and not self._completion_task.done():
await asyncio.wait(
{self._completion_task}, timeout=min(yield_time_ms, MAX_YIELD_MS) / 1000,
)
ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
_reap_pid(self.process.pid) # pyright: ignore[reportPrivateUsage]
elif yield_time_ms > 0:
await self._wait_for_buffered_output()
if self._completion_task.done():
await asyncio.shield(self._completion_task)
if self.cleanup_error is not None:
raise RuntimeError(f"session {self.session_id} cleanup failed: {self.cleanup_error}")
async with self._lock:
stdout, stdout_truncated = self._stdout.drain()
@@ -261,22 +349,36 @@ class _ExecSession:
output_parts.append(f"STDERR:\n{stderr}")
output = "\n".join(output_parts)
output, response_truncated = _truncate_output(output, max_output_chars)
now = time.monotonic()
return _SessionPoll(
output=output,
done=self.process.returncode is not None,
done=self.finished_at is not None,
exit_code=self.process.returncode,
elapsed_s=max(0.0, time.monotonic() - self.started_at),
timed_out=self._timed_out,
terminated=terminated,
elapsed_s=max(0.0, (self.finished_at or now) - self.started_at),
finish_reason=self.finish_reason,
stopping=self.stopping,
output_idle_s=self.output_idle_s(now),
idle_timeout=self.idle_timeout,
remaining_s=self.remaining_s(now),
stdin_closed=stdin_closed,
truncated_chars=stdout_truncated + stderr_truncated + response_truncated,
output_incomplete=self._output_incomplete,
execution_error=self._execution_error,
)
async def kill(self) -> None:
# A cancelled poll must not cancel the session's process-tree cleanup.
if self._kill_task is None or (
self._kill_task.done() and self.process.returncode is None
):
async def kill(self, reason: FinishReason = "cancelled") -> None:
await self._begin_stop(reason)
await asyncio.shield(self._completion_task)
async def _begin_stop(self, reason: FinishReason) -> None:
if self.finished_at is not None:
return
if self._execution_exited and self._stop_reason is None:
return
if self._stop_reason is None:
self._stop_reason = reason
if self._kill_task is None:
self.cleanup_error = None
self._kill_task = asyncio.create_task(self._kill())
self._kill_task.add_done_callback(self._on_kill_done)
await asyncio.shield(self._kill_task)
@@ -284,6 +386,8 @@ class _ExecSession:
def _on_kill_done(self, task: asyncio.Task[None]) -> None:
error = None if task.cancelled() else task.exception()
if error is not None:
self.cleanup_error = str(error)
self._state_changed.set()
logger.opt(exception=error if tool_log_content_allowed() else False).error(
"Failed to terminate exec session {}", self.session_id,
)
@@ -293,36 +397,19 @@ class _ExecSession:
async def _kill(self) -> None:
from nanobot.agent.tools.shell import ExecTool
try:
if self._process_tree:
await ExecTool._kill_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
else:
await ExecTool._kill_process(self.process) # pyright: ignore[reportPrivateUsage]
finally:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(
asyncio.gather(
self._stdout_task,
self._stderr_task,
return_exceptions=True,
),
timeout=2.0,
)
async def _wait_for_buffered_output(self) -> None:
deadline = time.monotonic() + OUTPUT_DRAIN_GRACE_S
while time.monotonic() < deadline:
async with self._lock:
if self._stdout.has_output or self._stderr.has_output:
return
await asyncio.sleep(0.01)
if self._process_tree:
await ExecTool._kill_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
else:
await ExecTool._kill_process(self.process) # pyright: ignore[reportPrivateUsage]
self._stop_complete.set()
class ExecSessionManager:
def __init__(self, *, max_sessions: int = 8, idle_timeout: int = 1800) -> None:
def __init__(self, *, max_sessions: int = 8, result_retention: int = 1800) -> None:
self.max_sessions = max_sessions
self.idle_timeout = idle_timeout
self.result_retention = result_retention
self._sessions: dict[str, _ExecSession] = {}
self._starting: dict[str, tuple[str | None, asyncio.Task[_ExecSession]]] = {}
self._lock = asyncio.Lock()
self._closed = False
@@ -338,32 +425,86 @@ class ExecSessionManager:
yield_time_ms: int,
max_output_chars: int,
owner_session_key: str | None = None,
idle_timeout: int = 300,
idle_action: Literal["report", "terminate"] = "report",
stdin: int = asyncio.subprocess.PIPE,
until_exit: bool = False,
) -> tuple[str, _SessionPoll]:
async with self._lock:
if self._closed:
raise RuntimeError("exec session manager is closed")
await self._cleanup_locked()
if len(self._sessions) >= self.max_sessions:
raise RuntimeError(f"maximum exec sessions reached ({self.max_sessions})")
process = await self._spawn(command, cwd, env, shell_program, login)
self._cleanup_finished_locked()
if len(self._sessions) + len(self._starting) >= self.max_sessions:
finished = [
(session.finished_at, session_id)
for session_id, session in self._sessions.items()
if session.finished_at is not None
]
if not finished:
raise RuntimeError(f"maximum exec sessions reached ({self.max_sessions})")
self._sessions.pop(min(finished)[1])
session_id = uuid.uuid4().hex[:12]
session = _ExecSession(
session_id=session_id,
process=process,
command=shlex.join(command) if isinstance(command, list) else command,
cwd=cwd,
timeout=timeout,
owner_session_key=owner_session_key,
process_tree=True,
)
self._sessions[session_id] = session
poll = await session.poll(yield_time_ms, max_output_chars)
launch = asyncio.create_task(self._launch(
session_id=session_id, command=command, cwd=cwd, env=env,
timeout=timeout, shell_program=shell_program, login=login,
owner_session_key=owner_session_key, idle_timeout=idle_timeout,
idle_action=idle_action, stdin=stdin,
))
self._starting[session_id] = (owner_session_key, launch)
try:
session = await launch
if until_exit:
await session.wait_exit()
poll = await session.poll(yield_time_ms, max_output_chars)
except asyncio.CancelledError:
if launch.done() and not launch.cancelled() and launch.exception() is None:
await launch.result().kill("cancelled")
async with self._lock:
self._sessions.pop(session_id, None)
raise
finally:
async with self._lock:
self._starting.pop(session_id, None)
if poll.done:
async with self._lock:
self._sessions.pop(session_id, None)
return session_id, poll
async def _launch(
self, *, session_id: str, command: str | list[str], cwd: str,
env: dict[str, str], timeout: int | None, shell_program: str | None,
login: bool, owner_session_key: str | None, idle_timeout: int,
idle_action: Literal["report", "terminate"], stdin: int,
) -> _ExecSession:
session: _ExecSession | None = None
try:
started_at = time.monotonic()
process = await self._spawn(command, cwd, env, shell_program, login, stdin=stdin)
session = _ExecSession(
session_id=session_id, process=process,
command=shlex.join(command) if isinstance(command, list) else command,
cwd=cwd, timeout=timeout, owner_session_key=owner_session_key,
process_tree=True, idle_timeout=idle_timeout, idle_action=idle_action,
started_at=started_at,
)
async with self._lock:
if self._closed or session_id not in self._starting:
raise RuntimeError("exec session owner closed during startup")
self._sessions[session_id] = session
return session
except BaseException:
if session is not None:
try:
await session.kill("owner_closed")
except BaseException:
async with self._lock:
self._sessions[session_id] = session
raise
raise
finally:
async with self._lock:
self._starting.pop(session_id, None)
async def write(
self,
*,
@@ -376,7 +517,7 @@ class ExecSessionManager:
owner_session_key: str | None = None,
) -> _SessionPoll:
async with self._lock:
await self._cleanup_locked()
self._cleanup_finished_locked()
session = self._sessions.get(session_id)
if session is None:
raise KeyError(session_id)
@@ -398,7 +539,6 @@ class ExecSessionManager:
poll = await session.poll(
yield_time_ms,
max_output_chars,
terminated=terminate,
stdin_closed=stdin_closed,
)
if poll.done:
@@ -408,7 +548,7 @@ class ExecSessionManager:
async def list(self, *, owner_session_key: str | None = None) -> list[ExecSessionInfo]:
async with self._lock:
await self._cleanup_locked()
self._cleanup_finished_locked()
now = time.monotonic()
return [
ExecSessionInfo(
@@ -416,10 +556,14 @@ class ExecSessionManager:
command=session.command,
cwd=session.cwd,
elapsed_s=max(0.0, now - session.started_at),
idle_s=max(0.0, now - session.last_access),
remaining_s=max(0.0, session.deadline - now),
idle_s=session.output_idle_s(now),
remaining_s=session.remaining_s(now),
returncode=session.process.returncode,
owner_session_key=session.owner_session_key,
idle_timeout=session.idle_timeout,
stopping=session.stopping,
finish_reason=session.finish_reason,
cleanup_error=session.cleanup_error,
)
for session_id, session in sorted(self._sessions.items())
if session.owner_session_key == owner_session_key
@@ -431,26 +575,9 @@ class ExecSessionManager:
self._closed = True
sessions: list[_ExecSession] = list(self._sessions.values())
self._sessions.clear()
results: list[None | BaseException] = list(await asyncio.gather(
*(session.kill() for session in sessions),
return_exceptions=True,
))
failures: list[tuple[_ExecSession, BaseException]] = [
(session, result)
for session, result in zip(sessions, results, strict=True)
if isinstance(result, BaseException)
]
if failures:
async with self._lock:
for session, _ in failures:
self._sessions[session.session_id] = session
if len(failures) == 1:
raise failures[0][1]
raise BaseExceptionGroup(
"failed to close exec sessions",
[result for _, result in failures],
)
return len(sessions)
launches = [task for _, task in self._starting.values()]
self._starting.clear()
return await self._stop_owned(sessions, launches, "shutdown")
async def terminate_by_owner(self, owner_session_key: str) -> int:
"""Terminate all sessions owned by owner_session_key. Returns count."""
@@ -459,38 +586,61 @@ class ExecSessionManager:
for sid, s in list(self._sessions.items()):
if s.owner_session_key == owner_session_key:
victims.append(self._sessions.pop(sid))
launches = [
task for owner, task in self._starting.values() if owner == owner_session_key
]
for sid, (owner, _) in list(self._starting.items()):
if owner == owner_session_key:
self._starting.pop(sid)
return await self._stop_owned(victims, launches, "owner_closed")
async def _stop_owned(
self, sessions: list[_ExecSession], launches: list[asyncio.Task[_ExecSession]],
reason: FinishReason,
) -> int:
results: list[None | BaseException] = list(await asyncio.gather(
*(s.kill() for s in victims),
*(session.kill(reason) for session in sessions),
self._cancel_launches(launches),
return_exceptions=True,
))
failures: list[tuple[_ExecSession, BaseException]] = [
startup_error = results.pop()
failures = [
(session, result)
for session, result in zip(victims, results, strict=True)
for session, result in zip(sessions, results, strict=True)
if isinstance(result, BaseException)
]
if failures:
async with self._lock:
for session, _ in failures:
self._sessions[session.session_id] = session
if len(failures) == 1:
raise failures[0][1]
raise BaseExceptionGroup(
"failed to terminate exec sessions by owner",
[result for _, result in failures],
)
return len(victims)
errors = [result for _, result in failures]
if isinstance(startup_error, BaseException):
errors.append(startup_error)
if len(errors) == 1:
raise errors[0]
if errors:
raise BaseExceptionGroup("failed to stop owned exec sessions", errors)
return len(sessions) + len(launches)
async def _cleanup_locked(self) -> None:
@staticmethod
async def _cancel_launches(launches: list[asyncio.Task[_ExecSession]]) -> None:
for task in launches:
task.cancel()
results = await asyncio.gather(*launches, return_exceptions=True)
errors = [result for result in results if isinstance(result, Exception)]
if errors:
raise ExceptionGroup("failed to cancel exec startup", errors)
def _cleanup_finished_locked(self) -> None:
now = time.monotonic()
stale = [
session_id
for session_id, session in self._sessions.items()
if now - session.last_access > self.idle_timeout
if session.finished_at is not None
and now - session.finished_at > self.result_retention
]
for session_id in stale:
session = self._sessions[session_id]
await session.kill()
self._sessions.pop(session_id, None)
self._sessions.pop(session_id)
async def _spawn(
self,
@@ -499,12 +649,14 @@ class ExecSessionManager:
env: dict[str, str],
shell_program: str | None,
login: bool,
*,
stdin: int = asyncio.subprocess.PIPE,
) -> asyncio.subprocess.Process:
from nanobot.agent.tools.shell import ExecTool
return await ExecTool._spawn( # pyright: ignore[reportPrivateUsage]
command, cwd, env, shell_program, login,
stdin=asyncio.subprocess.PIPE,
stdin=stdin,
process_tree=True,
)
@@ -531,16 +683,30 @@ def format_session_poll(session_id: str, poll: _SessionPoll) -> str:
parts = [poll.output] if poll.output else []
if poll.truncated_chars:
parts.append(f"({poll.truncated_chars:,} chars truncated from output)")
if poll.timed_out:
parts.append("Error: Command timed out; session was terminated.")
if poll.terminated and not poll.timed_out:
parts.append("Session terminated.")
if poll.finish_reason == "max_runtime":
parts.append("Error: Command timed out; session was terminated. Reason: max_runtime.")
elif poll.finish_reason == "idle_timeout":
parts.append("Error: Output silence limit reached; session was terminated. Reason: idle_timeout.")
elif poll.terminated:
parts.append(f"Session terminated. Reason: {poll.finish_reason}.")
elif poll.finish_reason == "execution_error":
parts.append(f"Error: Command output failed: {poll.execution_error}. Reason: execution_error.")
if poll.output_incomplete:
parts.append("Output collection ended before EOF; output may be incomplete.")
if poll.stdin_closed:
parts.append("Stdin closed.")
if poll.done:
parts.append(f"Exit code: {poll.exit_code}")
else:
parts.append(f"Process running. session_id: {session_id}")
state = "stopping" if poll.stopping else "running"
parts.append(f"Process {state}. session_id: {session_id}")
if poll.idle_timeout and poll.output_idle_s >= poll.idle_timeout:
parts.append(
f"Output silent for {poll.output_idle_s:.1f}s; "
"no stdout/stderr bytes observed. This does not establish a stall."
)
remaining = "unlimited" if poll.remaining_s is None else f"{poll.remaining_s:.1f}s"
parts.append(f"Runtime remaining: {remaining}")
parts.append(f"Elapsed: {poll.elapsed_s:.1f}s")
return "\n".join(parts) if parts else "(no output yet)"
@@ -654,7 +820,7 @@ class ExecSessionTool(Tool):
owner_session_key=current_request_session_key(),
)
result = format_session_poll(session_id, poll)
return ToolResult.error(result) if poll.timed_out else result
return ToolResult.error(result) if poll.failed else result
default_timeout_ms = (
DEFAULT_UNTIL_EXIT_MS
@@ -728,12 +894,12 @@ class ExecSessionTool(Tool):
result = format_session_poll(session_id, poll)
if wait_for is not None and not matched:
result += f"\nWait target not observed: {wait_for!r}"
elif until_exit and not poll.done:
if expired and not poll.done and not matched:
result += (
f"\nWait timed out after {timeout_ms / 1000:g}s; "
"session remains active."
)
return ToolResult.error(result) if poll.timed_out else result
return ToolResult.error(result) if poll.failed else result
@tool_parameters(tool_parameters_schema())
@@ -786,12 +952,19 @@ class ListExecSessionsTool(Tool):
command = " ".join(info.command.split())
if len(command) > 120:
command = command[:119] + "..."
status = "exited" if info.returncode is not None else "running"
status = "finished" if info.finish_reason is not None else (
"stopping" if info.stopping else "running"
)
remaining = "unlimited" if info.remaining_s is None else f"{info.remaining_s:.1f}s"
silent = bool(info.idle_timeout and info.idle_s >= info.idle_timeout)
lines.append(
f"{info.session_id} | {status} | elapsed={info.elapsed_s:.1f}s "
f"| idle={info.idle_s:.1f}s | remaining={info.remaining_s:.1f}s "
f"| output_idle={info.idle_s:.1f}s | silent={str(silent).lower()} "
f"| remaining={remaining} | reason={info.finish_reason or '-'} "
f"| cwd={info.cwd} | {command}"
)
if info.cleanup_error is not None:
lines.append(f"Cleanup failed: {info.cleanup_error}")
return "\n".join(lines)
except Exception as exc:
return ToolResult.error(f"Error listing exec sessions: {exc}")
+5 -1
View File
@@ -296,7 +296,11 @@ def _snapshot_web_config(config: WebToolsConfig) -> dict[str, object]:
def _snapshot_exec_config(config: ExecToolConfig) -> dict[str, object]:
return {
"enable": config.enable,
"timeout": config.timeout,
"max_runtime": config.max_runtime,
"max_runtime_limit": config.max_runtime_limit,
"idle_timeout": config.idle_timeout,
"idle_action": config.idle_action,
"timeout": config.max_runtime,
"path_prepend": config.path_prepend,
"path_append": config.path_append,
"sandbox": config.sandbox,
+81 -99
View File
@@ -13,12 +13,12 @@ import sys
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path, PureWindowsPath
from typing import Any, Protocol, cast
from typing import Any, Literal, Protocol, cast
from urllib.parse import unquote
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.context import ToolContext, current_request_session_key
from nanobot.agent.tools.exec_session import (
DEFAULT_EXEC_SESSION_MANAGER,
@@ -38,7 +38,6 @@ from nanobot.agent.tools.schema import (
tool_parameters_schema,
)
from nanobot.agent.tools.shell_config import ExecToolConfig
from nanobot.agent.tools.shell_output import ShellOutputFilter
from nanobot.config.paths import get_media_dir
from nanobot.security.workspace_access import current_scope_allows_loopback, current_tool_workspace
from nanobot.security.workspace_policy import is_path_within
@@ -101,16 +100,26 @@ class _PreparedCommand:
login: bool
@tool_parameters(
tool_parameters_schema(
def _exec_parameters(config: ExecToolConfig) -> dict[str, Any]:
return tool_parameters_schema(
command=StringSchema("The shell command to execute"),
cmd=StringSchema("Compatibility alias for command"),
working_dir=StringSchema("Optional working directory for the command"),
workdir=StringSchema("Compatibility alias for working_dir"),
timeout=IntegerSchema(
description="Hard timeout in seconds (default 60, max 600).",
max_runtime=IntegerSchema(
description=(
"Hard runtime budget in seconds. Omit for the configured default "
f"({'unlimited' if config.max_runtime == 0 else str(config.max_runtime) + 's'}). "
f"Explicit requests must not exceed {config.max_runtime_limit}s. "
"Output does not extend the budget."
),
minimum=1,
maximum=600,
maximum=config.max_runtime_limit,
),
timeout=IntegerSchema(
description="Compatibility alias for max_runtime; cannot be combined with it.",
minimum=1,
maximum=config.max_runtime_limit,
),
shell=StringSchema(
(
@@ -144,7 +153,8 @@ class _PreparedCommand:
nullable=True,
),
)
)
class ExecTool(Tool):
"""Tool to execute shell commands."""
_scopes = {"core", "subagent"}
@@ -164,7 +174,10 @@ class ExecTool(Tool):
cfg = ctx.config.exec
return cls(
working_dir=ctx.workspace,
timeout=cfg.timeout,
max_runtime=cfg.max_runtime,
max_runtime_limit=cfg.max_runtime_limit,
idle_timeout=cfg.idle_timeout,
idle_action=cfg.idle_action,
restrict_to_workspace=ctx.config.restrict_to_workspace,
webui_allow_local_service_access=ctx.config.webui_allow_local_service_access,
sandbox=cfg.sandbox,
@@ -180,7 +193,7 @@ class ExecTool(Tool):
def __init__(
self,
timeout: int = 60,
timeout: int | None = None,
working_dir: str | None = None,
deny_patterns: list[str] | None = None,
allow_patterns: list[str] | None = None,
@@ -194,8 +207,20 @@ class ExecTool(Tool):
sandbox_rw_binds: list[str] | None = None,
allowed_env_keys: list[str] | None = None,
session_manager: ExecSessionManager | None = None,
*,
max_runtime: int | None = None,
max_runtime_limit: int | None = None,
idle_timeout: int = 300,
idle_action: Literal["report", "terminate"] = "report",
):
self.timeout = timeout
if timeout is not None and max_runtime is not None:
raise ValueError("timeout and max_runtime are mutually exclusive")
values: dict[str, Any] = {"idle_timeout": idle_timeout, "idle_action": idle_action}
if (runtime := max_runtime if max_runtime is not None else timeout) is not None:
values["max_runtime"] = runtime
if max_runtime_limit is not None:
values["max_runtime_limit"] = max_runtime_limit
self._exec_config = ExecToolConfig.model_validate(values)
self.working_dir = working_dir
self.sandbox = sandbox
self.deny_patterns = (deny_patterns or []) + [
@@ -233,8 +258,13 @@ class ExecTool(Tool):
def name(self) -> str:
return "exec"
_MAX_TIMEOUT = 600
_MAX_OUTPUT = 10_000
@property
def parameters(self) -> dict[str, Any]:
return _exec_parameters(self._exec_config)
@property
def timeout(self) -> int:
return self._exec_config.max_runtime
# Kernel device files safe as stdio redirect targets (#3599).
_BENIGN_DEVICE_PATHS: frozenset[str] = frozenset({
@@ -251,7 +281,7 @@ class ExecTool(Tool):
@property
def description(self) -> str:
return "Execute a shell command."
return "Execute a shell command. timeout and max_runtime are mutually exclusive."
@property
def exclusive(self) -> bool:
@@ -264,6 +294,7 @@ class ExecTool(Tool):
login: bool | None = None, yield_time_ms: int | None = None,
max_output_chars: int | None = None,
max_output_tokens: int | None = None,
max_runtime: int | None = None,
**kwargs: Any,
) -> str:
command = command or cmd
@@ -273,73 +304,18 @@ class ExecTool(Tool):
if max_output_chars is None:
max_output_chars = max_output_tokens
prepared = self._prepare_command(command, working_dir, timeout, shell, login)
if timeout is not None and max_runtime is not None:
return ToolResult.error("Error: timeout and max_runtime are mutually exclusive.")
try:
prepared = self._prepare_command(
command, working_dir, max_runtime if max_runtime is not None else timeout,
shell, login,
)
except ValueError as exc:
return ToolResult.error(f"Error: {exc}")
if isinstance(prepared, str):
return prepared
if yield_time_ms is not None:
return await self._execute_session(prepared, yield_time_ms, max_output_chars)
process: asyncio.subprocess.Process | None = None
try:
process = await self._spawn(
prepared.command,
prepared.cwd,
prepared.env,
prepared.shell_program,
prepared.login,
process_tree=True,
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=prepared.timeout,
)
except asyncio.TimeoutError:
await self._kill_process_tree(process)
return ToolResult.error(f"Error: Command timed out after {prepared.timeout} seconds")
except asyncio.CancelledError:
await self._kill_process_tree(process)
raise
# Safety-net reap: asyncio *should* have reaped the child via
# communicate(), but in containers the child-watcher sometimes
# misses it, leaving a zombie.
_reap_pid(process.pid)
output_parts: list[str] = []
stdout_text = ShellOutputFilter().feed(stdout.decode("utf-8", errors="replace"))
if stdout_text:
output_parts.append(stdout_text)
stderr_text = ShellOutputFilter().feed(stderr.decode("utf-8", errors="replace"))
if stderr_text.strip():
output_parts.append(f"STDERR:\n{stderr_text}")
output_parts.append(f"\nExit code: {process.returncode}")
result = "\n".join(output_parts) if output_parts else "(no output)"
max_len = clamp_session_int(max_output_chars, self._MAX_OUTPUT, 1000, MAX_OUTPUT_CHARS)
if len(result) > max_len:
half = max_len // 2
result = (
result[:half]
+ f"\n\n... ({len(result) - max_len:,} chars truncated) ...\n\n"
+ result[-half:]
)
self._release_process_tree(process)
return result
except Exception as e:
# Kill and reap the child if it was spawned but an unexpected
# error prevented communicate() from completing.
if process is not None:
await self._kill_process_tree(process)
return ToolResult.error(f"Error executing command: {str(e)}")
return await self._execute_session(prepared, yield_time_ms, max_output_chars)
async def _execute_session(
self,
@@ -355,7 +331,14 @@ class ExecTool(Tool):
timeout=prepared.timeout,
shell_program=prepared.shell_program,
login=prepared.login,
yield_time_ms=clamp_session_int(yield_time_ms, DEFAULT_YIELD_MS, 0, MAX_YIELD_MS),
yield_time_ms=(
0 if yield_time_ms is None
else clamp_session_int(yield_time_ms, DEFAULT_YIELD_MS, 0, MAX_YIELD_MS)
),
until_exit=yield_time_ms is None,
stdin=(asyncio.subprocess.DEVNULL if yield_time_ms is None else asyncio.subprocess.PIPE),
idle_timeout=self._exec_config.idle_timeout,
idle_action=self._exec_config.idle_action,
owner_session_key=current_request_session_key(),
max_output_chars=clamp_session_int(
max_output_chars,
@@ -365,23 +348,23 @@ class ExecTool(Tool):
),
)
result = format_session_poll(session_id, poll)
return ToolResult.error(result) if poll.timed_out else result
if not poll.done and yield_time_ms is not None:
result += "\nInitial wait ended; session remains active."
return ToolResult.error(result) if poll.failed else result
except Exception as exc:
return ToolResult.error(f"Error executing command: {exc}")
def _resolve_timeout(self, timeout: int | None) -> int | None:
"""Resolve the effective hard timeout in seconds (None = no limit).
A per-call timeout supplied by the model stays capped at _MAX_TIMEOUT so
the LLM cannot request unbounded execution. The config-level default
(self.timeout) may exceed that cap, and 0 disables the limit entirely
for trusted long-running tasks (#3595).
"""
if timeout:
return min(timeout, self._MAX_TIMEOUT)
if self.timeout and self.timeout > 0:
return self.timeout
return None
def _resolve_timeout(self, timeout: object) -> int | None:
"""Resolve a hard budget without changing the caller's requested duration."""
if timeout is not None:
if isinstance(timeout, bool) or not isinstance(timeout, int):
raise ValueError("max_runtime must be an integer number of seconds")
if not 1 <= timeout <= self._exec_config.max_runtime_limit:
raise ValueError(
f"max_runtime must be between 1 and {self._exec_config.max_runtime_limit} seconds"
)
return timeout
return self.timeout or None
def _prepare_command(
self,
@@ -735,17 +718,16 @@ class ExecTool(Tool):
else:
try:
os.killpg(process.pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
except ProcessLookupError:
pass
if process.returncode is None:
with suppress(ProcessLookupError):
process.kill()
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(process.wait(), timeout=5.0)
finally:
await asyncio.wait_for(process.wait(), timeout=5.0)
if owner is not None:
ExecTool._drop_process_tree_owner(process)
finally:
_reap_pid(process.pid)
@staticmethod
+29 -2
View File
@@ -1,6 +1,9 @@
"""Execution configuration shared by shell/session tools and the root schema."""
from pydantic import Field
from collections.abc import Mapping
from typing import Literal, cast
from pydantic import AliasChoices, Field, model_validator
from nanobot.config_base import Base
@@ -8,7 +11,13 @@ from nanobot.config_base import Base
class ExecToolConfig(Base):
"""Shell exec tool configuration."""
enable: bool = True
timeout: int = Field(default=60, ge=0) # Hard timeout (s); 0 = no limit. Not capped by the per-call max.
max_runtime: int = Field(
default=3600, ge=0,
validation_alias=AliasChoices("maxRuntime", "max_runtime", "timeout"),
)
max_runtime_limit: int = Field(default=86400, gt=0)
idle_timeout: int = Field(default=300, ge=0)
idle_action: Literal["report", "terminate"] = "report"
path_prepend: str = ""
path_append: str = ""
sandbox: str = ""
@@ -17,3 +26,21 @@ class ExecToolConfig(Base):
allowed_env_keys: list[str] = Field(default_factory=list)
allow_patterns: list[str] = Field(default_factory=list)
deny_patterns: list[str] = Field(default_factory=list)
@model_validator(mode="before")
@classmethod
def _reject_runtime_alias_conflict(cls, value: object) -> object:
if isinstance(value, Mapping):
value = cast(Mapping[object, object], value)
if "timeout" in value and ("maxRuntime" in value or "max_runtime" in value):
raise ValueError("Use maxRuntime or legacy timeout, not both")
return value
@property
def timeout(self) -> int:
"""Legacy hard-runtime setting backed by ``max_runtime``."""
return self.max_runtime
@timeout.setter
def timeout(self, value: int) -> None:
self.max_runtime = value
+53 -1
View File
@@ -5,7 +5,8 @@ from pathlib import Path
from typing import Any, ClassVar, Literal, cast
from pydantic import AliasChoices, ConfigDict, Field, PrivateAttr, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic.fields import FieldInfo
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
from nanobot.agent.tools.cli_apps_config import CliAppsToolConfig
from nanobot.agent.tools.filesystem_config import FileToolsConfig
@@ -457,6 +458,44 @@ class ToolsConfig(Base):
ssrf_whitelist: list[str] = Field(default_factory=list) # CIDR ranges to exempt from SSRF blocking (e.g. ["100.64.0.0/10"] for Tailscale)
class _ExecRuntimeConfigSource(PydanticBaseSettingsSource):
"""Merge shell runtime aliases using the normal settings-source precedence."""
def __init__(self, source: PydanticBaseSettingsSource) -> None:
super().__init__(source.settings_cls)
self._source = source
def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
return self._source.get_field_value(field, field_name)
def __call__(self) -> dict[str, Any]:
data = self._source()
tools: object = data.get("tools")
if not isinstance(tools, dict):
return data
tools = cast(dict[str, Any], tools)
execution: object = tools.get("exec")
if not isinstance(execution, dict):
return data
execution = cast(dict[str, Any], execution)
if "timeout" in execution and ("maxRuntime" in execution or "max_runtime" in execution):
# Preserve same-source conflicts for the configuration model to reject.
return data
aliases = ("maxRuntime", "max_runtime", "timeout")
previous_tools: object = self.current_state.get("tools")
if not any(name in execution for name in aliases) or not isinstance(previous_tools, dict):
return data
previous_tools = cast(dict[str, Any], previous_tools)
previous_execution: object = previous_tools.get("exec")
if not isinstance(previous_execution, dict):
return data
previous_execution = cast(dict[str, Any], previous_execution)
if not any(name in previous_execution for name in aliases):
return data
execution = {name: value for name, value in execution.items() if name not in aliases}
return {**data, "tools": {**tools, "exec": execution}}
class Config(BaseSettings):
"""Root configuration for nanobot."""
@@ -475,6 +514,19 @@ class Config(BaseSettings):
serialization_alias="modelPresets",
)
@classmethod
def settings_customise_sources(
cls,
settings_cls: type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
return tuple(_ExecRuntimeConfigSource(source) for source in (
init_settings, env_settings, dotenv_settings, file_secret_settings,
))
def bind_source_path(self, path: Path) -> None:
"""Record the config file that owns instance-level runtime data."""
self._source_path = path.expanduser().resolve(strict=False)
+9
View File
@@ -60,6 +60,9 @@ RUNTIME_CONFIG_PATHS = (
def _parent(config: Config, path: str) -> tuple[BaseModel, str]:
# Keep the existing WebUI editor on the canonical hard-runtime field.
if path == "tools.exec.timeout":
path = "tools.exec.max_runtime"
parent: BaseModel = config
*parts, leaf = path.split(".")
for part in parts:
@@ -128,6 +131,12 @@ def update_runtime_config(
raise WebUISettingsError("gateway.port: must be at most 65535")
if "api.timeout" in values and validated.api.timeout > 3600:
raise WebUISettingsError("api.timeout: must be at most 3600 seconds")
if "tools.exec.timeout" in values:
limit = validated.tools.exec.max_runtime_limit
if validated.tools.exec.max_runtime > limit:
raise WebUISettingsError(
f"tools.exec.timeout: enter 1–{limit} seconds, or 0 for no time limit"
)
for path in ("gateway.host", "api.host", "tools.image_generation.save_dir"):
if path in values:
parent, leaf = _parent(validated, path)
+1
View File
@@ -144,6 +144,7 @@ def system_settings_payload(
**network_safety_payload(config),
"mcp_server_count": len(config.tools.mcp_servers),
"exec_enabled": exec_config.enable,
"exec_max_runtime_limit": exec_config.max_runtime_limit,
"exec_sandbox": exec_config.sandbox or None,
"exec_path_prepend_set": bool(exec_config.path_prepend),
"exec_path_append_set": bool(exec_config.path_append),