Skip to content

Your lightweight open-source personal agent.

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

chengyongru6310a39bacdb
diff --git a/docs/configuration.md b/docs/configuration.md
index fcaac4ac8..a25a10daa 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -2270,7 +2270,11 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets]
| `tools.maxSessionMessagesPerMinute` | `6` | Maximum messages one source session may send during any rolling 60-second window. Additional sends are rejected to stop runaway agent loops. |
| `tools.exec.sandbox` | `""` | Sandbox backend for shell commands. `"bwrap"` (Linux) or `"seatbelt"` (macOS) restricts filesystem access to the workspace (read-write), media (read-only), required system paths and configured extra binds. The workspace's parent is denied except for allowed roots; keep secrets outside the workspace and binds. Automatically enables workspace restriction for file tools. `"bwrap"` requires bubblewrap (`apt install bubblewrap`; pre-installed in Docker). `"seatbelt"` uses macOS `sandbox-exec(1)`; it sets `HOME` and `TMPDIR` to the workspace rather than sharing host temporary directories. Use `mktemp "$TMPDIR/job.XXXXXX"` for macOS shell scratch files. Neither backend restricts network access. Windows logs a warning and runs commands without OS sandboxing. |
| `tools.exec.enable` | `true` | When `false`, the shell `exec` tool is not registered at all. Use this to completely disable shell command execution. |
-| `tools.exec.timeout` | `60` | Default hard timeout in seconds for shell commands. Config values may exceed the per-call tool cap; set `0` to disable the hard timeout for trusted long-running commands. |
+| `tools.exec.maxRuntime` | `3600` | Default hard runtime in seconds for shell commands, measured from process start even while output is arriving. Set `0` only in trusted configuration to allow unlimited runtime. |
+| `tools.exec.maxRuntimeLimit` | `86400` | Positive upper bound in seconds for explicit model-requested hard runtimes. Independent of `maxRuntime`; it does not limit or change the trusted default. |
+| `tools.exec.idleTimeout` | `300` | Seconds without stdout or stderr before the idle action applies. Set `0` to disable inactivity checks. |
+| `tools.exec.idleAction` | `"report"` | `"report"` reports inactivity without stopping the command; `"terminate"` stops it. |
+| `tools.exec.timeout` | alias | Legacy name for `maxRuntime`, not an inactivity timeout. Existing explicit values, including `0`, keep their hard-runtime meaning. Do not set both names. |
| `tools.exec.pathPrepend` | `""` | Extra directories to prepend to `PATH` when running shell commands. Use this when configured tools should win executable lookup precedence, such as a Python virtual environment's `bin` or `Scripts` directory. |
| `tools.exec.pathAppend` | `""` | Extra directories to append to `PATH` when running shell commands (e.g. `/usr/sbin` for `ufw`). |
| `tools.exec.sandboxRoBinds` | `[]` | Extra absolute paths to expose read-only inside the exec sandbox (`--ro-bind-try` for `"bwrap"`, an SBPL `file-read*` rule for `"seatbelt"`), such as `/home/user/.local/bin` or `/home/user/.cargo/bin` when those paths are also in `pathPrepend`/`pathAppend`. These roots are also accepted by the shell absolute-path guard only while a sandbox is active. Bind only directories whose contents are safe for agent commands to read; paths equal to or containing the active workspace are ignored so they cannot uncover its masked parent directory. |
@@ -2286,6 +2290,36 @@ To diagnose a path error, the agent can call `my(action="check", key="workspace_
**Docker security**: The official Docker image runs as a non-root user (`nanobot`, UID 1000) with bubblewrap pre-installed. The default `docker-compose.yml` drops all Linux capabilities except the `CHOWN`, `SETGID`, and `SETUID` capabilities required by the root entrypoint to initialize bind-mount ownership and become UID 1000. It enables `no-new-privileges` so the final non-root process cannot regain those bootstrap capabilities, and keeps Docker's default AppArmor/seccomp profiles enabled. If you enable `"tools.exec.sandbox": "bwrap"` inside Docker, start Compose with `docker-compose.bwrap.yml` as an additional override so bubblewrap can create nested namespaces. The host must also allow unprivileged user namespaces; the override cannot bypass a host-level namespace restriction.
+### Shell command timing
+
+Shell commands have separate hard-runtime and inactivity checks. By default, a command can run for up to one hour. Five minutes without stdout or stderr produces an inactivity report but does not kill it. Output resets the inactivity clock; it never extends the hard-runtime deadline. A command that keeps printing can still reach its hard limit.
+
+Configure these defaults under `tools.exec` in `config.json`, then restart the gateway:
+
+```json
+{
+ "tools": {
+ "exec": {
+ "maxRuntime": 3600,
+ "maxRuntimeLimit": 86400,
+ "idleTimeout": 300,
+ "idleAction": "report"
+ }
+ }
+}
+```
+
+All durations are integer seconds. Snake-case configuration names (`max_runtime`, `max_runtime_limit`, `idle_timeout`, and `idle_action`) are also accepted; saved configuration uses camelCase. The command runtime control in Settings changes the hard-runtime default. Choose a preset, enter a custom duration in whole seconds up to `maxRuntimeLimit`, or select **No time limit**. Longer trusted defaults can be set in `config.json`; editing other settings preserves them. The agent can inspect the loaded defaults with `my(action="check", key="exec_config")`.
+
+The model may explicitly request a different hard runtime up to `maxRuntimeLimit`. This positive limit applies only to explicit tool-call arguments, not to the configured default. `maxRuntime` may exceed it or be `0` for unlimited runtime; changing `maxRuntime` does not change `maxRuntimeLimit`, which defaults to 86400 seconds. When the model omits the runtime argument, the command uses the trusted default. The model cannot explicitly request unlimited runtime. Set `idleTimeout` to `0` as well if a trusted command must run without either timing check.
+
+For existing configurations, `timeout` remains a hard-runtime alias: `"timeout": 60` still stops a command after 60 seconds, and `"timeout": 0` still means no hard deadline. Use either `timeout` or `maxRuntime`, not both.
+
+The tool result distinguishes a hard-runtime termination from inactivity. With `idleAction: "report"`, a silent command continues running under its hard-runtime limit. With `idleAction: "terminate"`, inactivity stops the command and the result reports that reason. Both limits apply without polling. Commands are cleaned up when they finish, reach an enforced limit, or their owning session is cancelled or deleted; normal operation does not require manual process management. `yield_time_ms` and an `exec_session` wait timeout only control how long a tool call waits before returning; neither stops the command nor resets its runtime or inactivity clock.
+
+Silence is not proof that a command is stuck: builds, downloads, and buffered programs can be quiet while working. Only bytes received through stdout or stderr count as activity; output redirected to files is not observed, and reading logs does not refresh the inactivity clock. Inactivity checks do not detect prompts or supply answers. Choose `"terminate"` only when stopping a quiet command is acceptable, and use a finite hard runtime when total execution time must remain bounded. Shell sessions are not durable jobs and should not be used as a replacement for a scheduler or service manager. A command that detaches a background service and exits is not a managed job; these timing checks do not manage that service afterward.
+
+
## Pairing
Pairing lets users get access to the bot through a simple code exchange — no config editing required. This works for both new users and existing users connecting from a new channel (e.g. someone already approved on Telegram now setting up Discord).
diff --git a/nanobot/agent/tools/exec_session.py b/nanobot/agent/tools/exec_session.py
index 3ecb45275..dce775e88 100644
--- a/nanobot/agent/tools/exec_session.py
+++ b/nanobot/agent/tools/exec_session.py
@@ -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)
- async def _watch_timeout(self) -> None:
- """Enforce the hard deadline even when nobody polls this session."""
+ @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_for(
- self.process.wait(), timeout=max(0.0, self.deadline - time.monotonic()),
+ 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:
+ """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)
-
- async def _cleanup_locked(self) -> None:
+ 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)
+
+ @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}")
diff --git a/nanobot/agent/tools/runtime_control.py b/nanobot/agent/tools/runtime_control.py
index 9929e47d1..a35a78228 100644
--- a/nanobot/agent/tools/runtime_control.py
+++ b/nanobot/agent/tools/runtime_control.py
@@ -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,
diff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.py
index cad8ad738..da2160671 100644
--- a/nanobot/agent/tools/shell.py
+++ b/nanobot/agent/tools/shell.py
@@ -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"),
+ 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=config.max_runtime_limit,
+ ),
timeout=IntegerSchema(
- description="Hard timeout in seconds (default 60, max 600).",
+ description="Compatibility alias for max_runtime; cannot be combined with it.",
minimum=1,
- maximum=600,
+ 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 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
+ if timeout is not None and max_runtime is not None:
+ return ToolResult.error("Error: timeout and max_runtime are mutually exclusive.")
try:
- process = await self._spawn(
- prepared.command,
- prepared.cwd,
- prepared.env,
- prepared.shell_program,
- prepared.login,
- process_tree=True,
+ prepared = self._prepare_command(
+ command, working_dir, max_runtime if max_runtime is not None else timeout,
+ shell, login,
)
-
- 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)}")
+ except ValueError as exc:
+ return ToolResult.error(f"Error: {exc}")
+ if isinstance(prepared, str):
+ return prepared
+ 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
diff --git a/nanobot/agent/tools/shell_config.py b/nanobot/agent/tools/shell_config.py
index 8010c85a9..d30afea15 100644
--- a/nanobot/agent/tools/shell_config.py
+++ b/nanobot/agent/tools/shell_config.py
@@ -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
diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py
index 1f0c93a58..1a2eaf3dc 100644
--- a/nanobot/config/schema.py
+++ b/nanobot/config/schema.py
@@ -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)
diff --git a/nanobot/webui/settings_runtime.py b/nanobot/webui/settings_runtime.py
index 301ab0967..05a1540b3 100644
--- a/nanobot/webui/settings_runtime.py
+++ b/nanobot/webui/settings_runtime.py
@@ -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)
diff --git a/nanobot/webui/settings_system.py b/nanobot/webui/settings_system.py
index 763b64d00..824308c8e 100644
--- a/nanobot/webui/settings_system.py
+++ b/nanobot/webui/settings_system.py
@@ -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),
diff --git a/tests/config/test_shell_config.py b/tests/config/test_shell_config.py
new file mode 100644
index 000000000..d939c9190
--- /dev/null
+++ b/tests/config/test_shell_config.py
@@ -0,0 +1,213 @@
+import json
+from unittest.mock import MagicMock
+
+import pytest
+from pydantic import ValidationError
+
+from nanobot.agent.tools.shell_config import ExecToolConfig
+from nanobot.config.errors import ConfigLoadError
+from nanobot.config.loader import load_config, save_config
+from nanobot.config.schema import Config
+
+
+def test_exec_timing_defaults() -> None:
+ config = Config().tools.exec
+
+ assert config.max_runtime == 3600
+ assert config.max_runtime_limit == 86400
+ assert config.idle_timeout == 300
+ assert config.idle_action == "report"
+ assert config.timeout == config.max_runtime
+
+
[email protected]("values", [
+ {"maxRuntime": 172800, "maxRuntimeLimit": 14400, "idleTimeout": 90, "idleAction": "terminate"},
+ {"max_runtime": 172800, "max_runtime_limit": 14400, "idle_timeout": 90, "idle_action": "terminate"},
+ {"timeout": 172800, "maxRuntimeLimit": 14400, "idleTimeout": 90, "idleAction": "terminate"},
+])
+def test_exec_timing_aliases_and_serialization(values) -> None:
+ config = ExecToolConfig.model_validate(values)
+ dumped = config.model_dump(by_alias=True)
+
+ assert config.max_runtime == 172800
+ assert config.max_runtime_limit == 14400
+ assert config.idle_timeout == 90
+ assert config.idle_action == "terminate"
+ assert dumped["maxRuntime"] == 172800
+ assert dumped["maxRuntimeLimit"] == 14400
+ assert dumped["idleTimeout"] == 90
+ assert dumped["idleAction"] == "terminate"
+ assert not {"timeout", "max_runtime", "max_runtime_limit", "idle_timeout", "idle_action"} & dumped.keys()
+ assert ExecToolConfig.model_validate_json(config.model_dump_json(by_alias=True)) == config
+
+
[email protected]("name", ["timeout", "maxRuntime", "max_runtime"])
[email protected]("runtime", [0, 60, 3600, 172800])
+def test_exec_runtime_does_not_raise_default_model_limit(name: str, runtime: int) -> None:
+ config = ExecToolConfig.model_validate({name: runtime})
+
+ assert config.max_runtime == runtime
+ assert config.timeout == runtime
+ assert config.max_runtime_limit == 86400
+
+
[email protected]("name", ["maxRuntime", "max_runtime"])
+def test_exec_rejects_simultaneous_legacy_and_canonical_runtime(name: str) -> None:
+ with pytest.raises(ValidationError, match="not both"):
+ Config.model_validate({"tools": {"exec": {"timeout": 60, name: 60}}})
+
+
[email protected]("values", [
+ {"maxRuntime": -1},
+ {"timeout": -1},
+ {"idleTimeout": -1},
+ {"maxRuntime": 1.5},
+ {"idleTimeout": 1.5},
+ {"maxRuntimeLimit": 0},
+ {"maxRuntimeLimit": -1},
+ {"idleAction": "ignore"},
+])
+def test_exec_rejects_invalid_timing_configuration(values) -> None:
+ with pytest.raises(ValidationError):
+ Config.model_validate({"tools": {"exec": values}})
+
+
+def test_exec_unlimited_default_keeps_a_positive_model_limit() -> None:
+ config = ExecToolConfig(max_runtime=0, max_runtime_limit=1, idle_timeout=0)
+
+ assert config.max_runtime == 0
+ assert config.max_runtime_limit == 1
+ assert config.idle_timeout == 0
+ assert ExecToolConfig(max_runtime=1, max_runtime_limit=1).max_runtime == 1
+
+
+def test_legacy_timeout_property_writes_canonical_runtime() -> None:
+ config = ExecToolConfig()
+ config.timeout = 42
+ assert config.max_runtime == 42
+ assert config.model_dump(by_alias=True)["maxRuntime"] == 42
+
+ config.max_runtime = 0
+ assert config.timeout == 0
+ assert "timeout" not in config.model_dump()
+
+
+def test_legacy_exec_config_loads_and_saves_canonical_fields(tmp_path) -> None:
+ path = tmp_path / "config.json"
+ path.write_text(json.dumps({"tools": {"exec": {"timeout": 172800}}}), encoding="utf-8")
+
+ config = load_config(path)
+ save_config(config, path)
+ restored = load_config(path).tools.exec
+ saved = json.loads(path.read_text(encoding="utf-8"))["tools"]["exec"]
+
+ assert restored.max_runtime == 172800
+ assert restored.max_runtime_limit == 86400
+ assert saved["maxRuntime"] == 172800
+ assert saved["maxRuntimeLimit"] == 86400
+ assert saved["idleTimeout"] == 300
+ assert saved["idleAction"] == "report"
+ assert "timeout" not in saved
+
+
[email protected]("runtime", [0, 42, 14400])
+def test_legacy_webui_timeout_editor_updates_canonical_runtime(tmp_path, runtime: int) -> None:
+ from nanobot.webui.settings_api import update_runtime_config_settings
+
+ path = tmp_path / "config.json"
+ save_config(Config.model_validate({"tools": {"exec": {
+ "maxRuntime": 7200, "maxRuntimeLimit": 14400,
+ "idleTimeout": 90, "idleAction": "terminate",
+ }}}), path)
+
+ result = update_runtime_config_settings(
+ {"tools.exec.timeout": runtime}, local_browser=True, config_path=path,
+ )
+ config = load_config(path).tools.exec
+
+ assert config.max_runtime == runtime
+ assert config.timeout == runtime
+ assert config.max_runtime_limit == 14400
+ assert config.idle_timeout == 90
+ assert config.idle_action == "terminate"
+ assert result["runtime_config"]["tools.exec.timeout"] == runtime
+ assert result["requires_restart"]
+ assert json.loads(path.read_text(encoding="utf-8"))["tools"]["exec"]["maxRuntime"] == runtime
+
+
[email protected](("file_name", "env_name"), [
+ ("timeout", "TIMEOUT"),
+ ("timeout", "MAX_RUNTIME"),
+ ("maxRuntime", "TIMEOUT"),
+])
+def test_exec_runtime_source_precedence_survives_settings_saves(
+ tmp_path, monkeypatch, file_name: str, env_name: str,
+) -> None:
+ from nanobot.webui.settings_api import update_agent_settings, update_runtime_config_settings
+
+ path = tmp_path / "config.json"
+ path.write_text(json.dumps({"tools": {"exec": {file_name: 60}}}), encoding="utf-8")
+ monkeypatch.setenv(f"NANOBOT_TOOLS__EXEC__{env_name}", "90")
+ assert load_config(path).tools.exec.max_runtime == 60
+
+ result = update_runtime_config_settings(
+ {"tools.exec.timeout": 42}, local_browser=True, config_path=path,
+ )
+ assert result["runtime_config"]["tools.exec.timeout"] == 42
+
+ result = update_agent_settings({"timezone": ["Asia/Shanghai"]}, config_path=path)
+ assert result["runtime_config"]["tools.exec.timeout"] == 42
+ assert load_config(path).tools.exec.max_runtime == 42
+ saved = json.loads(path.read_text(encoding="utf-8"))["tools"]["exec"]
+ assert saved["maxRuntime"] == 42
+ assert "timeout" not in saved
+
+
[email protected]("source", ["file", "environment"])
+def test_exec_load_rejects_runtime_aliases_from_the_same_source(tmp_path, monkeypatch, source):
+ path = tmp_path / "config.json"
+ data = {"tools": {"exec": {"timeout": 60, "maxRuntime": 90}}}
+ if source == "file":
+ path.write_text(json.dumps(data), encoding="utf-8")
+ else:
+ monkeypatch.setenv("NANOBOT_TOOLS", json.dumps(data["tools"]))
+
+ with pytest.raises(ConfigLoadError):
+ load_config(path)
+
+
+def test_exec_runtime_source_precedence_covers_both_canonical_spellings(monkeypatch):
+ monkeypatch.setenv("NANOBOT_TOOLS__EXEC", json.dumps({
+ "maxRuntime": 90, "max_runtime": 120,
+ }))
+
+ config = Config.model_validate({"tools": {"exec": {"timeout": 60}}})
+
+ assert config.tools.exec.max_runtime == 60
+
+
+async def test_my_exec_config_reports_configured_timing(tmp_path) -> None:
+ from nanobot.agent.loop import AgentLoop
+ from nanobot.agent.tools.self import MyTool
+ from nanobot.bus.queue import MessageBus
+
+ config = Config.model_validate({"tools": {"exec": {
+ "timeout": 172800, "idleTimeout": 0, "idleAction": "terminate",
+ }}})
+ provider = MagicMock()
+ provider.get_default_model.return_value = "test-model"
+ loop = AgentLoop(
+ bus=MessageBus(), provider=provider, workspace=tmp_path,
+ tools_config=config.tools, model="test-model",
+ )
+ tool = loop.tools.get("my")
+ assert isinstance(tool, MyTool)
+
+ expected = {
+ "max_runtime": 172800, "max_runtime_limit": 86400,
+ "idle_timeout": 0, "idle_action": "terminate", "timeout": 172800,
+ }
+ for key, value in expected.items():
+ result = await tool.execute(action="check", key=f"exec_config.{key}")
+ assert result == f"exec_config.{key}: {value!r}"
diff --git a/tests/tools/test_exec_platform.py b/tests/tools/test_exec_platform.py
index 1396c645f..abced9710 100644
--- a/tests/tools/test_exec_platform.py
+++ b/tests/tools/test_exec_platform.py
@@ -22,6 +22,25 @@ _WINDOWS_ENV_KEYS = {
}
+class _CompletedProcess:
+ """A finished subprocess with the stream/wait protocol used by the collector."""
+
+ def __init__(self, stdout: bytes, stderr: bytes = b"", returncode: int = 0) -> None:
+ self.pid = 12345
+ self.returncode = returncode
+ self.stdin = None
+ self.stdout = asyncio.StreamReader()
+ self.stderr = asyncio.StreamReader()
+ self.stdout.feed_data(stdout)
+ self.stdout.feed_eof()
+ self.stderr.feed_data(stderr)
+ self.stderr.feed_eof()
+
+ async def wait(self) -> int:
+ await asyncio.sleep(0)
+ return self.returncode
+
+
class _FakeWindowsJob:
creation_flags = 0
@@ -373,15 +392,13 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_unix_uses_env_var_in_fixed_export(self):
"""On Unix, path_append must not be interpolated into shell source."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"ok", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"ok")
captured_cmd = None
captured_env = {}
async def capture_spawn(
- cmd, cwd, env, shell_program=None, login=True, *, process_tree=False,
+ cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
):
nonlocal captured_cmd
captured_cmd = cmd
@@ -404,9 +421,7 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_unix_path_prepend_uses_env_var_in_fixed_export(self):
"""On Unix, path_prepend must not be interpolated into shell source."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"ok", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"ok")
captured_cmd = None
captured_env = {}
@@ -434,9 +449,7 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_unix_path_prepend_and_append_order(self):
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"ok", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"ok")
captured_cmd = None
captured_env = {}
@@ -467,14 +480,12 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_windows_modifies_env(self):
"""On Windows, path_append is appended to PATH in the env dict."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"ok", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"ok")
captured_env = {}
async def capture_spawn(
- cmd, cwd, env, shell_program=None, login=True, *, process_tree=False,
+ cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
):
captured_env.update(env)
return mock_proc
@@ -492,9 +503,7 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_windows_path_prepend_and_append_order(self):
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"ok", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"ok")
captured_env = {}
@@ -529,9 +538,7 @@ class TestSandboxPlatform:
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_skipped_on_windows(self, backend):
"""Configured Unix backends preserve the Windows native fallback."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"ok", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"ok")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -549,9 +556,7 @@ class TestSandboxPlatform:
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_applied_on_unix(self, backend):
"""On Unix, sandbox wrapping should still happen normally."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"sandboxed", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"sandboxed")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
@@ -570,9 +575,7 @@ class TestSandboxPlatform:
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_receives_configured_bind_roots(self, tmp_path, backend):
"""Configured bind roots should be forwarded to the sandbox wrapper."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"sandboxed", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"sandboxed")
tool_bin = tmp_path / "tool-bin"
tool_cache = tmp_path / "tool-cache"
@@ -606,54 +609,61 @@ class TestSandboxPlatform:
class TestExecuteEndToEnd:
@pytest.mark.asyncio
- async def test_windows_full_path(self):
+ @pytest.mark.parametrize(
+ "yield_time_ms, stdin",
+ [(None, asyncio.subprocess.DEVNULL), (1000, asyncio.subprocess.PIPE)],
+ )
+ async def test_windows_full_path(self, yield_time_ms, stdin):
"""Full execute() flow on Windows: env, spawn, output formatting."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"hello world\r\n", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"hello world\r\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
- patch.object(ExecTool, "_spawn", return_value=mock_proc),
+ patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool()
- result = await tool.execute(command="echo hello world")
+ result = await tool.execute(command="echo hello world", yield_time_ms=yield_time_ms)
assert "hello world" in result
assert "Exit code: 0" in result
+ assert "session_id:" not in result
+ assert mock_spawn.call_args.kwargs.get("stdin", asyncio.subprocess.DEVNULL) == stdin
+ assert mock_spawn.call_args.kwargs["process_tree"] is True
@pytest.mark.asyncio
- async def test_unix_full_path(self):
+ @pytest.mark.parametrize(
+ "yield_time_ms, stdin",
+ [(None, asyncio.subprocess.DEVNULL), (1000, asyncio.subprocess.PIPE)],
+ )
+ async def test_unix_full_path(self, yield_time_ms, stdin):
"""Full execute() flow on Unix: env, spawn, output formatting."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"hello world\n", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"hello world\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
- patch.object(ExecTool, "_spawn", return_value=mock_proc),
+ patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool()
- result = await tool.execute(command="echo hello world")
+ result = await tool.execute(command="echo hello world", yield_time_ms=yield_time_ms)
assert "hello world" in result
assert "Exit code: 0" in result
+ assert "session_id:" not in result
+ assert mock_spawn.call_args.kwargs.get("stdin", asyncio.subprocess.DEVNULL) == stdin
+ assert mock_spawn.call_args.kwargs["process_tree"] is True
@pytest.mark.asyncio
async def test_execute_defaults_to_non_login_shell(self):
"""The public execute path must not silently request a login shell."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"ok\n", b"")
- mock_proc.returncode = 0
captured_login = []
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=None, *, stdin=None, process_tree=False,
):
captured_login.append(login)
- return mock_proc
+ return _CompletedProcess(b"ok\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
@@ -735,9 +745,7 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_multiline_python_uses_powershell(self):
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"1\n2\n", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"1\n2\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -757,9 +765,7 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_multiline_node_uses_powershell(self):
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"1\n", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"1\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -778,9 +784,7 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_single_line_uses_powershell(self):
"""Single-line commands also route through PowerShell now."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"1\n", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"1\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -795,9 +799,7 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_unix_unchanged(self):
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"1\n2\n", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"1\n2\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
@@ -821,9 +823,7 @@ class TestResolveShellWindows:
@pytest.mark.asyncio
async def test_shell_powershell_accepted(self):
"""shell='powershell' should resolve and route through PowerShell."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b"hello\n", b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b"hello\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -843,9 +843,7 @@ class TestResolveShellWindows:
@pytest.mark.asyncio
async def test_shell_cmd_accepted(self):
"""shell='cmd' should preserve the command string for cmd.exe parsing."""
- mock_proc = AsyncMock()
- mock_proc.communicate.return_value = (b'"a & b"\n', b"")
- mock_proc.returncode = 0
+ mock_proc = _CompletedProcess(b'"a & b"\n')
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
diff --git a/tests/tools/test_exec_session_capacity.py b/tests/tools/test_exec_session_capacity.py
new file mode 100644
index 000000000..c9149ba4a
--- /dev/null
+++ b/tests/tools/test_exec_session_capacity.py
@@ -0,0 +1,105 @@
+from __future__ import annotations
+
+import asyncio
+import re
+import shutil
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+from nanobot.agent.tools.context import RequestContext, request_context
+from nanobot.agent.tools.exec_session import (
+ ExecSessionManager,
+ ExecSessionTool,
+ ListExecSessionsTool,
+)
+from nanobot.agent.tools.registry import is_tool_error_result
+from nanobot.agent.tools.rg import RgTool
+from nanobot.agent.tools.shell import ExecTool
+
+
+async def _start_gated(tool: ExecTool, gate: Path) -> str:
+ code = (
+ "import time; from pathlib import Path; "
+ f"gate=Path({str(gate)!r})\n"
+ "while not gate.exists(): time.sleep(0.01)\n"
+ "print('retained result')"
+ )
+ result = await tool.execute(command=[sys.executable, "-u", "-c", code], yield_time_ms=0)
+ match = re.search(r"session_id:\s*([0-9a-f]+)", result)
+ assert match, result
+ return match.group(1)
+
+
+async def _wait_finished(manager: ExecSessionManager, owner: str | None, session_id: str) -> None:
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ sessions = await manager.list(owner_session_key=owner)
+ if any(info.session_id == session_id and info.finish_reason == "exit" for info in sessions):
+ return
+ await asyncio.sleep(0.01)
+ raise AssertionError(f"session {session_id} did not finish")
+
+
[email protected]("tool_name", [
+ "exec",
+ pytest.param("rg", marks=pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")),
+])
+async def test_finished_results_do_not_block_other_owner_tools(tmp_path, tool_name):
+ manager = ExecSessionManager(max_sessions=2)
+ tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
+ session_tool = ExecSessionTool(manager=manager)
+ owner_a = RequestContext(channel="cli", chat_id="a", session_key="cli:a")
+ owner_b = RequestContext(channel="cli", chat_id="b", session_key="cli:b")
+ try:
+ with request_context(owner_a):
+ oldest = await _start_gated(tool, tmp_path / "first")
+ newest = await _start_gated(tool, tmp_path / "second")
+ for gate, sid in [("first", oldest), ("second", newest)]:
+ (tmp_path / gate).touch()
+ await _wait_finished(manager, owner_a.session_key, sid)
+
+ with request_context(owner_b):
+ assert await ListExecSessionsTool(manager=manager).execute() == "No active exec sessions."
+ assert is_tool_error_result(await session_tool.execute(session_id=newest, timeout_ms=0))
+ if tool_name == "rg":
+ result = await RgTool(working_dir=str(tmp_path), session_manager=manager).execute(
+ args=["--version"],
+ )
+ assert "ripgrep" in result
+ else:
+ result = await tool.execute(command=[sys.executable, "-c", "print('other owner')"])
+ assert "other owner" in result
+ assert not is_tool_error_result(result), result
+ assert "Exit code: 0" in result
+
+ with request_context(owner_a):
+ remaining = await manager.list(owner_session_key=owner_a.session_key)
+ assert [info.session_id for info in remaining] == [newest]
+ result = await session_tool.execute(session_id=newest, timeout_ms=0)
+ assert "retained result" in result
+ assert "Exit code: 0" in result
+ finally:
+ await manager.close_all()
+
+
+async def test_capacity_preserves_running_work_and_bounds_completed_results(tmp_path):
+ manager = ExecSessionManager(max_sessions=2)
+ tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
+ try:
+ running = await _start_gated(tool, tmp_path / "running")
+ latest = await _start_gated(tool, tmp_path / "finished-0")
+ rejected = await tool.execute(command=[sys.executable, "-c", "print('over capacity')"])
+ assert is_tool_error_result(rejected)
+ assert "maximum exec sessions reached (2)" in rejected
+ for index in range(4):
+ (tmp_path / f"finished-{index}").touch()
+ await _wait_finished(manager, None, latest)
+ latest = await _start_gated(tool, tmp_path / f"finished-{index + 1}")
+ sessions = await manager.list()
+ assert {info.session_id for info in sessions} == {running, latest}
+ assert all(info.finish_reason is None for info in sessions)
+ finally:
+ await manager.close_all()
diff --git a/tests/tools/test_exec_session_startup.py b/tests/tools/test_exec_session_startup.py
new file mode 100644
index 000000000..87f3561ee
--- /dev/null
+++ b/tests/tools/test_exec_session_startup.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+import asyncio
+import sys
+
+import pytest
+
+from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context
+from nanobot.agent.tools.exec_session import ExecSessionManager
+from nanobot.agent.tools.shell import ExecTool
+
+
+async def test_owner_cancellation_during_startup_preserves_other_execution(tmp_path, monkeypatch):
+ manager = ExecSessionManager(max_sessions=2)
+ tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
+ blocked_command = [sys.executable, "-u", "-c", "print('blocked launch')"]
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ spawn = manager._spawn
+
+ async def gated_spawn(command, cwd, env, shell_program, login, *, stdin):
+ if command == blocked_command:
+ entered.set()
+ await release.wait()
+ return await spawn(command, cwd, env, shell_program, login, stdin=stdin)
+
+ monkeypatch.setattr(manager, "_spawn", gated_spawn)
+ token = bind_request_context(RequestContext(channel="cli", chat_id="a", session_key="cli:a"))
+ try:
+ blocked = asyncio.create_task(tool.execute(command=blocked_command, yield_time_ms=0))
+ finally:
+ reset_request_context(token)
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=5)
+ token = bind_request_context(RequestContext(channel="cli", chat_id="b", session_key="cli:b"))
+ try:
+ other = await asyncio.wait_for(
+ tool.execute(command=[sys.executable, "-u", "-c", "print('other completed')"]),
+ timeout=10,
+ )
+ finally:
+ reset_request_context(token)
+ assert "other completed" in other
+ assert "Exit code: 0" in other
+ assert await asyncio.wait_for(manager.terminate_by_owner("cli:a"), timeout=5) == 1
+ with pytest.raises(asyncio.CancelledError):
+ await blocked
+ continued = await tool.execute(command=[sys.executable, "-u", "-c", "print('slot released')"])
+ assert "slot released" in continued
+ assert "Exit code: 0" in continued
+ finally:
+ release.set()
+ await asyncio.gather(blocked, return_exceptions=True)
+ await manager.close_all()
diff --git a/tests/tools/test_exec_session_timeout.py b/tests/tools/test_exec_session_timeout.py
index 2a1c70d3b..d70bdb367 100644
--- a/tests/tools/test_exec_session_timeout.py
+++ b/tests/tools/test_exec_session_timeout.py
@@ -51,7 +51,7 @@ async def test_exec_session_hard_timeout_kills_process_tree_without_polling(tmp_
assert not late_write.exists(), "the descendant wrote after the hard timeout"
assert session.process.returncode != 0
- final = await session_tool.execute(session_id=sid, timeout_ms=0)
+ final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=2000)
assert is_tool_error_result(final)
assert "Command timed out; session was terminated." in final
assert "parent started" in initial + final
@@ -105,7 +105,7 @@ async def test_exec_session_zero_config_timeout_allows_unpolled_longer_process(t
sid = _session_id(initial)
await asyncio.wait_for(manager._sessions[sid].process.wait(), timeout=5)
- final = await session_tool.execute(session_id=sid, timeout_ms=0)
+ final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=2000)
assert not is_tool_error_result(final)
assert "completed without deadline" in initial + final
assert "Exit code: 0" in final
diff --git a/tests/tools/test_exec_session_tools.py b/tests/tools/test_exec_session_tools.py
index 1bb8e3c6d..e362cb56d 100644
--- a/tests/tools/test_exec_session_tools.py
+++ b/tests/tools/test_exec_session_tools.py
@@ -65,6 +65,31 @@ def _session_id(output: str) -> str:
return match.group(1)
+def _session_process(
+ *,
+ stdout: asyncio.StreamReader | None = None,
+ stderr: asyncio.StreamReader | None = None,
+) -> tuple[SimpleNamespace, asyncio.Event]:
+ exited = asyncio.Event()
+ process = SimpleNamespace(pid=12345, stdout=stdout, stderr=stderr, returncode=None)
+
+ async def wait() -> int:
+ await exited.wait()
+ assert process.returncode is not None
+ return process.returncode
+
+ process.wait = wait
+ return process, exited
+
+
+async def _cancel_session_tasks(session: _ExecSession) -> None:
+ tasks = [session._stdout_task, session._stderr_task, session._completion_task]
+ tasks.extend(task for task in (session._timeout_task, session._kill_task) if task is not None)
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+
async def _poll_if_running(
initial: str,
tool: ExecSessionTool,
@@ -160,23 +185,29 @@ async def test_exec_session_preserves_utf8_across_stdout_and_stderr_chunks():
stderr_bytes = b"b" * 4094 + "🙂é".encode() + b"\xff"
stdout.feed_data(stdout_bytes[:4096])
stderr.feed_data(stderr_bytes[:4096])
+ process, exited = _session_process(stdout=stdout, stderr=stderr)
session = _ExecSession(
session_id="utf8-output",
- process=SimpleNamespace(stdout=stdout, stderr=stderr),
+ process=process,
command="test",
cwd=".",
timeout=None,
)
- await asyncio.sleep(0)
- stdout.feed_data(stdout_bytes[4096:])
- stderr.feed_data(stderr_bytes[4096:])
- stdout.feed_eof()
- stderr.feed_eof()
- await asyncio.gather(session._stdout_task, session._stderr_task)
+ try:
+ await asyncio.sleep(0)
+ stdout.feed_data(stdout_bytes[4096:])
+ stderr.feed_data(stderr_bytes[4096:])
+ stdout.feed_eof()
+ stderr.feed_eof()
+ process.returncode = 0
+ exited.set()
+ await asyncio.wait_for(session._completion_task, timeout=2)
- assert session._stdout.drain() == ("a" * 4095 + "你好🙂\ufffd", 0)
- assert session._stderr.drain() == ("b" * 4094 + "🙂é\ufffd", 0)
+ assert session._stdout.drain() == ("a" * 4095 + "你好🙂\ufffd", 0)
+ assert session._stderr.drain() == ("b" * 4094 + "🙂é\ufffd", 0)
+ finally:
+ await _cancel_session_tasks(session)
def test_exec_session_bounds_unpolled_stdout_and_stderr(tmp_path):
@@ -196,11 +227,9 @@ def test_exec_session_bounds_unpolled_stdout_and_stderr(tmp_path):
)
sid = _session_id(initial)
session = manager._sessions[sid]
- await asyncio.wait_for(session.process.wait(), timeout=15)
- await asyncio.wait_for(
- asyncio.gather(session._stdout_task, session._stderr_task),
- timeout=15,
- )
+ await asyncio.wait_for(session._completion_task, timeout=15)
+ assert session.finish_reason == "exit"
+ assert session.finished_at is not None
retained_stdout = session._stdout.retained_chars
retained_stderr = session._stderr.retained_chars
poll = await manager.write(
@@ -246,7 +275,7 @@ def test_exec_session_wait_for_keeps_aggregate_within_output_budget():
assert result.startswith("HEAD")
assert "Wait target not observed" not in result
assert "(8,000 chars truncated from output)" in result
- assert len(result) < 10100
+ assert len(result.partition("\n")[0]) == 10_000
def test_exec_session_wait_for_searches_before_response_truncation():
@@ -291,7 +320,7 @@ def test_exec_session_wait_for_searches_before_response_truncation():
assert observed_limits == [MAX_OUTPUT_CHARS]
assert "Wait target not observed" not in result
assert "(20,006 chars truncated from output)" in result
- assert len(result) < 10100
+ assert len(result.partition("\n")[0]) == 10_000
def test_exec_one_shot_accepts_max_output_tokens_alias(tmp_path):
@@ -424,7 +453,10 @@ def test_exec_session_preserves_completed_session_output_until_polled(tmp_path):
initial = await exec_tool.execute(command=command, yield_time_ms=50)
sid = _session_id(initial)
- await asyncio.wait_for(manager._sessions[sid].process.wait(), timeout=2)
+ session = manager._sessions[sid]
+ await asyncio.wait_for(session._completion_task, timeout=2)
+ assert session.finish_reason == "exit"
+ assert session.finished_at is not None
final = await stdin_tool.execute(session_id=sid, input="", timeout_ms=0)
return initial, final
@@ -832,8 +864,8 @@ def test_exec_session_manager_retains_and_aggregates_failed_cleanup():
assert len(exc_info.value.exceptions) == 2
assert manager._sessions == {first.session_id: first, second.session_id: second}
- first.kill.assert_awaited_once()
- second.kill.assert_awaited_once()
+ first.kill.assert_awaited_once_with("shutdown")
+ second.kill.assert_awaited_once_with("shutdown")
first.kill.side_effect = None
second.kill.side_effect = None
@@ -979,7 +1011,7 @@ def test_terminate_by_owner_retains_failed_sessions():
await manager.terminate_by_owner("cli:a")
assert manager._sessions == {session.session_id: session}
- session.kill.assert_awaited_once()
+ session.kill.assert_awaited_once_with("owner_closed")
session.kill.side_effect = None
assert await manager.terminate_by_owner("cli:a") == 1
@@ -988,26 +1020,48 @@ def test_terminate_by_owner_retains_failed_sessions():
asyncio.run(run())
-def test_stale_cleanup_retains_session_when_kill_fails():
+def test_result_retention_only_cleans_completed_sessions(tmp_path, monkeypatch):
async def run() -> None:
- manager = ExecSessionManager(idle_timeout=1)
- session = SimpleNamespace(
- session_id="stale-failed",
- owner_session_key="cli:a",
- last_access=time.monotonic() - 10,
- kill=AsyncMock(side_effect=OSError("termination failed")),
+ now = time.monotonic()
+ monkeypatch.setattr(
+ "nanobot.agent.tools.exec_session.time",
+ SimpleNamespace(monotonic=lambda: now),
+ )
+ manager = ExecSessionManager(result_retention=10)
+ tool = ExecTool(working_dir=str(tmp_path), max_runtime=0, session_manager=manager)
+ command = _python_command(
+ "import sys; print('ready', flush=True); "
+ "sys.stdin.read(); print('done', flush=True)"
)
- manager._sessions[session.session_id] = session
-
- with pytest.raises(OSError, match="termination failed"):
- await manager.list(owner_session_key="cli:a")
-
- assert manager._sessions == {session.session_id: session}
- session.kill.assert_awaited_once()
- session.kill.side_effect = None
- assert await manager.list(owner_session_key="cli:a") == []
- assert manager._sessions == {}
+ try:
+ initial = await tool.execute(command=command, yield_time_ms=0)
+ sid = _session_id(initial)
+ session = manager._sessions[sid]
+
+ now += 100
+ listing = await manager.list()
+ assert [info.session_id for info in listing] == [sid]
+ assert session.process.returncode is None
+ assert session.finished_at is None
+
+ assert await session.close_stdin() is None
+ await asyncio.wait_for(session._completion_task, timeout=10)
+ assert session.finish_reason == "exit"
+ assert session.finished_at == now
+ assert session._stdout.has_output
+
+ now += 9
+ listing = await manager.list()
+ assert [info.session_id for info in listing] == [sid]
+ assert listing[0].finish_reason == "exit"
+ assert listing[0].returncode == 0
+
+ now += 2
+ assert await manager.list() == []
+ assert manager._sessions == {}
+ finally:
+ await manager.close_all()
asyncio.run(run())
@@ -1055,7 +1109,7 @@ def test_agent_loop_shutdown_preserves_single_cleanup_error():
async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
- process = SimpleNamespace(stdout=None, stderr=None, returncode=None)
+ process, exited = _session_process()
session = _ExecSession(
session_id="shared-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1069,6 +1123,7 @@ async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
kill_started.set()
await release_kill.wait()
process.returncode = -9
+ exited.set()
kill_tree = AsyncMock(side_effect=kill_process_tree)
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_tree)
@@ -1092,16 +1147,18 @@ async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
release_kill.set()
await asyncio.wait_for(second, timeout=2)
assert process.returncode == -9
+ assert session.finish_reason == "cancelled"
+ assert session.finished_at is not None
kill_tree.assert_awaited_once_with(process)
finally:
release_kill.set()
await asyncio.gather(first, *([second] if second is not None else []), return_exceptions=True)
- await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
+ await _cancel_session_tasks(session)
@pytest.mark.parametrize("log_content", [True, False])
async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content):
- process = SimpleNamespace(stdout=None, stderr=None, returncode=None)
+ process, exited = _session_process()
session = _ExecSession(
session_id="retry-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1115,6 +1172,7 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
if attempts == 1:
raise OSError("temporary process-tree cleanup failure")
process.returncode = -9
+ exited.set()
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_process_tree)
records = []
@@ -1126,8 +1184,12 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
with pytest.raises(OSError, match="temporary process-tree cleanup failure"):
await session.kill()
assert process.returncode is None
+ assert session.finished_at is None
await session.kill()
assert process.returncode == -9
+ assert session.finish_reason == "cancelled"
+ assert session.finished_at is not None
+ assert session.cleanup_error is None
assert attempts == 2
assert len(records) == 1
assert (records[0]["exception"] is not None) is log_content
@@ -1135,12 +1197,11 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
finally:
reset_request_context(token)
logger.remove(sink)
- await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
+ await _cancel_session_tasks(session)
async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeypatch):
- exited = asyncio.Event()
- process = SimpleNamespace(stdout=None, stderr=None, returncode=None, wait=exited.wait)
+ process, exited = _session_process()
session = _ExecSession(
session_id="explicit-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1164,25 +1225,30 @@ async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeyp
await asyncio.wait_for(kill_started.wait(), timeout=2)
original_kill = session.kill
- async def join_existing_kill():
+ async def join_existing_kill(reason="cancelled"):
+ assert reason == "max_runtime"
watcher_joined.set()
- await original_kill()
+ await original_kill(reason)
monkeypatch.setattr(session, "kill", join_existing_kill)
session.deadline = time.monotonic() - 1
watcher = asyncio.create_task(session._watch_timeout())
await asyncio.wait_for(watcher_joined.wait(), timeout=2)
- assert not session._timed_out
+ assert session.finish_reason is None
+ assert session.stopping
assert not watcher.done()
kill_tree.assert_awaited_once_with(process)
release_kill.set()
await asyncio.wait_for(asyncio.gather(explicit_kill, watcher), timeout=2)
assert process.returncode == -9
- assert not session._timed_out
+ assert session.finish_reason == "cancelled"
+ poll = await session.poll(0, 1000)
+ assert poll.terminated
+ assert not poll.timed_out
kill_tree.assert_awaited_once_with(process)
finally:
release_kill.set()
await asyncio.gather(
explicit_kill, *([watcher] if watcher is not None else []), return_exceptions=True,
)
- await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
+ await _cancel_session_tasks(session)
diff --git a/tests/tools/test_rg_tool.py b/tests/tools/test_rg_tool.py
index 445157692..c2755c92d 100644
--- a/tests/tools/test_rg_tool.py
+++ b/tests/tools/test_rg_tool.py
@@ -182,7 +182,8 @@ async def test_direct_process_timeout(tmp_path):
result = await ExecTool(working_dir=str(tmp_path)).execute(
command=[sys.executable, "-c", "import time; time.sleep(20)"], timeout=1,
)
- assert "timed out after 1 seconds" in result
+ assert "Reason: max_runtime" in result
+ assert "Exit code:" in result
async def test_direct_process_cancellation_reaps_child(tmp_path, monkeypatch):
diff --git a/tests/tools/test_shell_execution_budgets.py b/tests/tools/test_shell_execution_budgets.py
new file mode 100644
index 000000000..6a0be4b02
--- /dev/null
+++ b/tests/tools/test_shell_execution_budgets.py
@@ -0,0 +1,592 @@
+from __future__ import annotations
+
+import asyncio
+import os
+import re
+import signal
+import sys
+import time
+from contextlib import suppress
+from pathlib import Path
+
+import pytest
+
+from nanobot.agent.tools.context import RequestContext, request_context
+from nanobot.agent.tools.exec_session import (
+ ExecSessionManager,
+ ExecSessionTool,
+ ListExecSessionsTool,
+)
+from nanobot.agent.tools.registry import is_tool_error_result
+from nanobot.agent.tools.shell import ExecTool
+
+
+def _python(code: str) -> list[str]:
+ return [sys.executable, "-u", "-c", code]
+
+
+def _session_id(output: str) -> str:
+ match = re.search(r"session_id:\s*([0-9a-f]+)", output)
+ assert match, output
+ return match.group(1)
+
+
+def _listed_ids(output: str) -> list[str]:
+ return re.findall(r"^([0-9a-f]+)\s*\|", output, flags=re.MULTILINE)
+
+
+def _exit_code(output: str) -> int:
+ match = re.search(r"Exit code:\s*(-?\d+)", output)
+ assert match, output
+ return int(match.group(1))
+
+
+def _silent_seconds(output: str) -> float:
+ match = re.search(r"Output silent[^\n]*?(\d+(?:\.\d+)?)\s*(?:s\b|seconds?\b)", output)
+ assert match, output
+ return float(match.group(1))
+
+
+def _elapsed_seconds(output: str) -> float:
+ match = re.search(r"Elapsed:\s*(\d+(?:\.\d+)?)s", output)
+ assert match, output
+ return float(match.group(1))
+
+
+async def _file_text(path: Path, *, timeout: float = 5) -> str:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if path.exists() and (text := path.read_text()):
+ return text
+ await asyncio.sleep(0.02)
+ raise AssertionError(f"subprocess did not write {path} within {timeout}s")
+
+
+def _pid_running(pid: int) -> bool:
+ if sys.platform == "win32":
+ import ctypes
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ kernel32.OpenProcess.restype = wintypes.HANDLE
+ kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
+ kernel32.WaitForSingleObject.restype = wintypes.DWORD
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ handle = kernel32.OpenProcess(0x00100000, False, pid) # SYNCHRONIZE
+ if not handle:
+ error = ctypes.get_last_error()
+ assert error == 87, f"OpenProcess({pid}) failed: {error}"
+ return False
+ try:
+ status = kernel32.WaitForSingleObject(handle, 0)
+ assert status in (0, 258), f"WaitForSingleObject({pid}) failed: {status}"
+ return status == 258 # WAIT_TIMEOUT
+ finally:
+ kernel32.CloseHandle(handle)
+
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ # A killed grandchild can remain a zombie until its new parent reaps it.
+ stat = Path(f"/proc/{pid}/stat")
+ with suppress(FileNotFoundError):
+ if stat.exists() and stat.read_text().rsplit(")", 1)[1].split()[0] == "Z":
+ return False
+ return True
+
+
+async def _pid_stopped(pid: int, *, timeout: float = 6) -> None:
+ deadline = time.monotonic() + timeout
+ while _pid_running(pid) and time.monotonic() < deadline:
+ await asyncio.sleep(0.03)
+ assert not _pid_running(pid), f"subprocess {pid} is still running after {timeout}s"
+
+
+async def _cleanup_pidfiles(*paths: Path) -> None:
+ pids = [int(path.read_text()) for path in paths if path.exists() and path.read_text()]
+ for pid in pids:
+ if _pid_running(pid):
+ with suppress(ProcessLookupError, OSError):
+ os.kill(pid, signal.SIGTERM if sys.platform == "win32" else signal.SIGKILL)
+ for pid in pids:
+ await _pid_stopped(pid, timeout=3)
+
+
+def _waiting_tree(parent_pidfile: Path, child_pidfile: Path) -> str:
+ child = (
+ "import os,time; from pathlib import Path; "
+ f"Path({str(child_pidfile)!r}).write_text(str(os.getpid())); "
+ "time.sleep(60)"
+ )
+ return (
+ "import os,subprocess,sys; from pathlib import Path; "
+ f"child=subprocess.Popen([sys.executable, '-u', '-c', {child!r}]); "
+ f"Path({str(parent_pidfile)!r}).write_text(str(os.getpid())); "
+ "child.wait()"
+ )
+
+
+async def test_trusted_default_runtime_can_exceed_model_request_limit():
+ manager = ExecSessionManager()
+ tool = ExecTool(
+ max_runtime=12, max_runtime_limit=1, idle_timeout=0, session_manager=manager,
+ )
+ try:
+ result = await tool.execute(command=_python(
+ "import time; time.sleep(1.2); print('trusted default completed')"
+ ))
+
+ assert not is_tool_error_result(result), result
+ assert "trusted default completed" in result
+ assert _exit_code(result) == 0
+ finally:
+ await manager.close_all()
+
+
+async def test_wait_timeout_leaves_stdin_gated_work_alive(tmp_path):
+ ready = tmp_path / "ready"
+ done = tmp_path / "done"
+ code = (
+ "import sys; from pathlib import Path; "
+ f"Path({str(ready)!r}).write_text('ready'); "
+ "print('waiting for input', flush=True); line=sys.stdin.readline().strip(); "
+ f"Path({str(done)!r}).write_text(line); "
+ "print('completed:' + line, flush=True)"
+ )
+ manager = ExecSessionManager()
+ tool = ExecTool(
+ working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
+ idle_timeout=1, session_manager=manager,
+ )
+ session_tool = ExecSessionTool(manager=manager)
+ list_tool = ListExecSessionsTool(manager=manager)
+ try:
+ initial = await tool.execute(command=_python(code), yield_time_ms=0)
+ sid = _session_id(initial)
+ assert await _file_text(ready) == "ready"
+
+ waited = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=200)
+
+ assert not is_tool_error_result(waited), waited
+ assert "Wait timed out after 0.2s; session remains active." in waited
+ assert f"Process running. session_id: {sid}" in waited
+ listing = await list_tool.execute()
+ assert _listed_ids(listing) == [sid]
+ assert "| running |" in listing
+
+ final = await session_tool.execute(
+ session_id=sid, input="finish after wait\n", until_exit=True, timeout_ms=5000,
+ )
+ assert not is_tool_error_result(final), final
+ assert "completed:finish after wait" in final
+ assert _exit_code(final) == 0
+ assert done.read_text() == "finish after wait"
+ finally:
+ await manager.close_all()
+
+
+async def test_default_idle_reporting_survives_unpolled_silence_and_reads(tmp_path):
+ ready = tmp_path / "ready"
+ done = tmp_path / "done"
+ code = (
+ "import sys; from pathlib import Path; "
+ f"Path({str(ready)!r}).write_text('ready'); "
+ "line=sys.stdin.readline().strip(); "
+ f"Path({str(done)!r}).write_text(line); print('silent work completed', flush=True)"
+ )
+ manager = ExecSessionManager(result_retention=1)
+ tool = ExecTool(
+ working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
+ idle_timeout=1, session_manager=manager,
+ )
+ session_tool = ExecSessionTool(manager=manager)
+ list_tool = ListExecSessionsTool(manager=manager)
+ try:
+ initial = await tool.execute(command=_python(code), yield_time_ms=0)
+ sid = _session_id(initial)
+ assert await _file_text(ready) == "ready"
+ await asyncio.sleep(1.25)
+
+ first = await session_tool.execute(session_id=sid, timeout_ms=0)
+ first_idle = _silent_seconds(first)
+ assert first_idle >= 1
+ assert f"Process running. session_id: {sid}" in first
+ listing = await list_tool.execute()
+ assert _listed_ids(listing) == [sid]
+ assert "| running |" in listing
+ await asyncio.sleep(0.35)
+ second = await session_tool.execute(session_id=sid, timeout_ms=0)
+ assert _silent_seconds(second) >= first_idle + 0.2
+ assert f"Process running. session_id: {sid}" in second
+
+ final = await session_tool.execute(
+ session_id=sid, input="still alive\n", until_exit=True, timeout_ms=5000,
+ )
+ assert not is_tool_error_result(final), final
+ assert "silent work completed" in final
+ assert _exit_code(final) == 0
+ assert done.read_text() == "still alive"
+ finally:
+ await manager.close_all()
+
+
+async def test_partial_stdout_and_stderr_bytes_refresh_idle_without_log_reads(tmp_path):
+ ready = tmp_path / "ready"
+ stdout_gate = tmp_path / "emit-stdout"
+ stderr_gate = tmp_path / "emit-stderr"
+ finish_gate = tmp_path / "finish"
+ stdout_ack = tmp_path / "stdout-written"
+ stderr_ack = tmp_path / "stderr-written"
+ done = tmp_path / "done"
+ code = (
+ "import os,time; from pathlib import Path; "
+ f"Path({str(ready)!r}).write_text('ready')\n"
+ f"while not Path({str(stdout_gate)!r}).exists(): time.sleep(0.02)\n"
+ "os.write(1, bytes([0xE2]))\n"
+ f"Path({str(stdout_ack)!r}).write_text('stdout')\n"
+ f"while not Path({str(stderr_gate)!r}).exists(): time.sleep(0.02)\n"
+ "os.write(2, bytes([0xE2]))\n"
+ f"Path({str(stderr_ack)!r}).write_text('stderr')\n"
+ f"while not Path({str(finish_gate)!r}).exists(): time.sleep(0.02)\n"
+ f"Path({str(done)!r}).write_text(Path({str(finish_gate)!r}).read_text())\n"
+ "print('byte-gated complete', flush=True)\n"
+ )
+ manager = ExecSessionManager()
+ tool = ExecTool(
+ working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
+ idle_timeout=2, idle_action="terminate", session_manager=manager,
+ )
+ session_tool = ExecSessionTool(manager=manager)
+ try:
+ initial = await tool.execute(command=_python(code), yield_time_ms=0)
+ sid = _session_id(initial)
+ assert await _file_text(ready) == "ready"
+ await asyncio.sleep(1.25)
+ stdout_gate.write_text("emit")
+ assert await _file_text(stdout_ack) == "stdout"
+
+ await asyncio.sleep(1.25)
+ stderr_gate.write_text("emit")
+ assert await _file_text(stderr_ack) == "stderr"
+
+ await asyncio.sleep(1.25)
+ finish_gate.write_text("finish")
+ final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=5000)
+ assert not is_tool_error_result(final), final
+ assert "byte-gated complete" in final
+ assert _exit_code(final) == 0
+ assert done.read_text() == "finish"
+ finally:
+ await manager.close_all()
+
+
+async def test_idle_termination_stops_owned_tree_without_tool_activity(tmp_path):
+ parent_pidfile = tmp_path / "parent.pid"
+ child_pidfile = tmp_path / "child.pid"
+ manager = ExecSessionManager()
+ tool = ExecTool(
+ working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
+ idle_timeout=2, idle_action="terminate", session_manager=manager,
+ )
+ session_tool = ExecSessionTool(manager=manager)
+ try:
+ initial = await tool.execute(
+ command=_python(_waiting_tree(parent_pidfile, child_pidfile)), yield_time_ms=0,
+ )
+ sid = _session_id(initial)
+ parent_pid = int(await _file_text(parent_pidfile))
+ child_pid = int(await _file_text(child_pidfile))
+ assert _pid_running(parent_pid)
+ assert _pid_running(child_pid)
+
+ # Observe OS process exit before making another tool or manager call.
+ await _pid_stopped(parent_pid)
+ await _pid_stopped(child_pid, timeout=3)
+ final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=3000)
+
+ assert is_tool_error_result(final), final
+ assert "idle_timeout" in final
+ assert _exit_code(final) != 0
+ finally:
+ try:
+ await manager.close_all()
+ finally:
+ await _cleanup_pidfiles(parent_pidfile, child_pidfile)
+
+
+async def test_hard_budget_counts_down_despite_output_and_repeated_waits(tmp_path):
+ pidfile = tmp_path / "process.pid"
+ code = (
+ "import os,time; from pathlib import Path; "
+ f"Path({str(pidfile)!r}).write_text(str(os.getpid())); n=0\n"
+ "while True:\n"
+ " n+=1\n"
+ " print('progress:' + str(n), flush=True)\n"
+ " time.sleep(0.15)\n"
+ )
+ manager = ExecSessionManager()
+ tool = ExecTool(
+ working_dir=str(tmp_path), max_runtime=3, max_runtime_limit=3,
+ idle_timeout=1, idle_action="terminate", session_manager=manager,
+ )
+ session_tool = ExecSessionTool(manager=manager)
+ try:
+ initial = await tool.execute(command=_python(code), yield_time_ms=0)
+ sid = _session_id(initial)
+ pid = int(await _file_text(pidfile))
+ before = (await manager.list())[0]
+
+ first = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=900)
+ second = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=900)
+
+ for waited in (first, second):
+ assert "Wait timed out after 0.9s; session remains active." in waited
+ assert "progress:" in waited
+ after = (await manager.list())[0]
+ assert before.remaining_s is not None and after.remaining_s is not None
+ assert after.remaining_s <= before.remaining_s - 1.4
+ assert after.idle_s < 0.7
+ assert _pid_running(pid)
+
+ await _pid_stopped(pid, timeout=5)
+ final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=3000)
+ assert is_tool_error_result(final), final
+ assert "max_runtime" in final
+ assert "progress:" in final
+ assert _exit_code(final) != 0
+ assert 2.5 <= _elapsed_seconds(final) <= 4.5
+ progress_counts = re.findall(r"progress:(\d+)", initial + first + second + final)
+ assert max(map(int, progress_counts)) >= 8
+ finally:
+ try:
+ await manager.close_all()
+ finally:
+ await _cleanup_pidfiles(pidfile)
+
+
+ ("early_root_exit", "stop_reason"),
+ [
+ pytest.param(False, "max_runtime", id="ordinary-root-hard-budget"),
+ pytest.param(True, "max_runtime", id="early-root-hard-budget"),
+ pytest.param(True, "owner_closed", id="early-root-owner-close"),
+ ],
+)
+async def test_execution_stop_stops_pipe_inheriting_child_after_root_exits(
+ tmp_path, monkeypatch, early_root_exit, stop_reason,
+):
+ parent_pidfile = tmp_path / "parent.pid"
+ child_pidfile = tmp_path / "child.pid"
+ release_root = tmp_path / "release-root"
+ release_child = tmp_path / "release-child"
+ delayed_effect = tmp_path / "delayed-effect"
+ child_code = (
+ "import os,time; from pathlib import Path; "
+ f"Path({str(child_pidfile)!r}).write_text(str(os.getpid()))\n"
+ f"while not Path({str(release_child)!r}).exists(): time.sleep(0.02)\n"
+ f"Path({str(delayed_effect)!r}).write_text('child escaped execution stop')\n"
+ )
+ parent_code = (
+ "import os,subprocess,sys,time; from pathlib import Path; "
+ f"Path({str(parent_pidfile)!r}).write_text(str(os.getpid())); "
+ f"subprocess.Popen([sys.executable, '-u', '-c', {child_code!r}]); "
+ "print('worker launched', flush=True)\n"
+ )
+ if not early_root_exit:
+ parent_code += f"while not Path({str(release_root)!r}).exists(): time.sleep(0.02)\n"
+
+ real_spawn = ExecTool._spawn
+ spawn_returned = asyncio.Event()
+
+ async def spawn_with_exit_order(*args, **kwargs):
+ process = await real_spawn(*args, **kwargs)
+ if early_root_exit:
+ # Root exit may precede spawn return; inherited pipes must remain intact.
+ async with asyncio.timeout(5):
+ while process.returncode is None:
+ await asyncio.sleep(0.005)
+ assert process.returncode == 0
+ else:
+ assert process.returncode is None
+ spawn_returned.set()
+ return process
+
+ monkeypatch.setattr(ExecTool, "_spawn", staticmethod(spawn_with_exit_order))
+ owner = RequestContext(channel="cli", chat_id="pipe-budget", session_key="cli:pipe-budget")
+ manager = ExecSessionManager()
+ max_runtime = 12 if stop_reason == "owner_closed" else 2
+ tool = ExecTool(
+ working_dir=str(tmp_path), max_runtime=max_runtime, max_runtime_limit=max_runtime,
+ idle_timeout=1, session_manager=manager,
+ )
+ initial_exec_task = None
+ try:
+ with request_context(owner):
+ initial_exec_task = asyncio.create_task(tool.execute(command=_python(parent_code)))
+ await asyncio.wait_for(spawn_returned.wait(), timeout=5)
+ parent_pid = int(await _file_text(parent_pidfile))
+ child_pid = int(await _file_text(child_pidfile))
+ release_root.write_text("root may exit")
+ await _pid_stopped(parent_pid, timeout=1)
+ assert _pid_running(child_pid)
+ assert not initial_exec_task.done()
+
+ if stop_reason == "owner_closed":
+ assert await asyncio.wait_for(
+ manager.terminate_by_owner(owner.session_key), timeout=6,
+ ) == 1
+ await _pid_stopped(child_pid, timeout=5)
+ release_child.write_text("perform the delayed write")
+ final = await asyncio.wait_for(initial_exec_task, timeout=3)
+
+ if stop_reason == "max_runtime":
+ assert is_tool_error_result(final), final
+ assert "Reason: max_runtime." in final
+ assert 1.5 <= _elapsed_seconds(final) <= 3.5
+ else:
+ assert not is_tool_error_result(final), final
+ assert "Session terminated. Reason: owner_closed." in final
+ assert "worker launched" in final
+ assert _exit_code(final) == 0 # Only the root exited successfully.
+ assert not delayed_effect.exists()
+ assert await manager.list(owner_session_key=owner.session_key) == []
+ finally:
+ try:
+ await _cleanup_pidfiles(parent_pidfile, child_pidfile)
+ finally:
+ try:
+ await asyncio.wait_for(manager.close_all(), timeout=6)
+ finally:
+ if initial_exec_task is not None:
+ initial_exec_task.cancel()
+ await asyncio.gather(initial_exec_task, return_exceptions=True)
+
+
+async def test_inline_work_reports_silence_then_hits_same_fixed_hard_budget(tmp_path):
+ pidfile = tmp_path / "process.pid"
+ gate = tmp_path / "emit-output"
+ ticks = tmp_path / "ticks"
+ code = (
+ "import os,time; from pathlib import Path; "
+ f"Path({str(pidfile)!r}).write_text(str(os.getpid()))\n"
+ f"while not Path({str(gate)!r}).exists(): time.sleep(0.02)\n"
+ "n=0\n"
+ "while True:\n"
+ " n+=1\n"
+ " print('inline-progress:' + str(n), flush=True)\n"
+ f" Path({str(ticks)!r}).write_text(str(n))\n"
+ " time.sleep(0.15)\n"
+ )
+ manager = ExecSessionManager()
+ tool = ExecTool(
+ working_dir=str(tmp_path), max_runtime=4, max_runtime_limit=4,
+ idle_timeout=1, session_manager=manager,
+ )
+ list_tool = ListExecSessionsTool(manager=manager)
+ inline_task = None
+ try:
+ inline_task = asyncio.create_task(tool.execute(command=_python(code)))
+ pid = int(await _file_text(pidfile))
+ await asyncio.sleep(1.25)
+
+ listing = await list_tool.execute()
+ assert len(_listed_ids(listing)) == 1, listing
+ assert "| running |" in listing
+ assert (await manager.list())[0].idle_s >= 1
+ assert not inline_task.done()
+ assert _pid_running(pid)
+
+ gate.write_text("emit")
+ assert int(await _file_text(ticks)) >= 1
+ await _pid_stopped(pid)
+ final = await asyncio.wait_for(inline_task, timeout=3)
+
+ assert is_tool_error_result(final), final
+ assert "inline-progress:" in final
+ assert "max_runtime" in final
+ assert _exit_code(final) != 0
+ assert 3.5 <= _elapsed_seconds(final) <= 5.5
+ assert await list_tool.execute() == "No active exec sessions."
+ finally:
+ try:
+ await manager.close_all()
+ finally:
+ if inline_task is not None:
+ inline_task.cancel()
+ await asyncio.gather(inline_task, return_exceptions=True)
+ await _cleanup_pidfiles(pidfile)
+
+
+async def test_owner_close_stops_inline_tree_and_preserves_other_owner_work(tmp_path):
+ parent_pidfile = tmp_path / "owner-a-parent.pid"
+ child_pidfile = tmp_path / "owner-a-child.pid"
+ survivor_pidfile = tmp_path / "owner-b.pid"
+ done = tmp_path / "owner-b-done"
+ survivor_code = (
+ "import os,sys; from pathlib import Path; "
+ f"Path({str(survivor_pidfile)!r}).write_text(str(os.getpid())); "
+ "print('owner-b-ready', flush=True); line=sys.stdin.readline().strip(); "
+ f"Path({str(done)!r}).write_text(line); print('owner-b-completed', flush=True)"
+ )
+ owner_a = RequestContext(channel="cli", chat_id="budget-a", session_key="cli:budget-a")
+ owner_b = RequestContext(channel="cli", chat_id="budget-b", session_key="cli:budget-b")
+ manager = ExecSessionManager()
+ tool = ExecTool(
+ working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
+ idle_timeout=1, session_manager=manager,
+ )
+ session_tool = ExecSessionTool(manager=manager)
+ list_tool = ListExecSessionsTool(manager=manager)
+ inline_task = None
+ try:
+ with request_context(owner_a):
+ inline_task = asyncio.create_task(tool.execute(
+ command=_python(_waiting_tree(parent_pidfile, child_pidfile)),
+ ))
+ parent_pid = int(await _file_text(parent_pidfile))
+ child_pid = int(await _file_text(child_pidfile))
+ owner_listing = await list_tool.execute()
+ owner_ids = _listed_ids(owner_listing)
+ assert len(owner_ids) == 1, owner_listing
+ sid_a = owner_ids[0]
+
+ with request_context(owner_b):
+ initial_b = await tool.execute(command=_python(survivor_code), yield_time_ms=0)
+ sid_b = _session_id(initial_b)
+ survivor_pid = int(await _file_text(survivor_pidfile))
+ assert _listed_ids(await list_tool.execute()) == [sid_b]
+ denied = await session_tool.execute(session_id=sid_a, terminate=True)
+ assert is_tool_error_result(denied), denied
+ assert denied == f"Error: exec session not found: {sid_a!r}"
+
+ assert _pid_running(parent_pid)
+ assert _pid_running(child_pid)
+ assert await manager.terminate_by_owner("cli:budget-a") == 1
+ await _pid_stopped(parent_pid, timeout=3)
+ await _pid_stopped(child_pid, timeout=3)
+ final_a = await asyncio.wait_for(inline_task, timeout=3)
+ assert "Session terminated." in final_a
+ assert _exit_code(final_a) != 0
+
+ with request_context(owner_b):
+ assert _pid_running(survivor_pid)
+ listing = await list_tool.execute()
+ assert _listed_ids(listing) == [sid_b]
+ assert "| running |" in listing
+ final_b = await session_tool.execute(
+ session_id=sid_b, input="owner-b-success\n", until_exit=True, timeout_ms=5000,
+ )
+ assert not is_tool_error_result(final_b), final_b
+ assert "owner-b-completed" in final_b
+ assert _exit_code(final_b) == 0
+ assert done.read_text() == "owner-b-success"
+ finally:
+ try:
+ await manager.close_all()
+ finally:
+ if inline_task is not None:
+ inline_task.cancel()
+ await asyncio.gather(inline_task, return_exceptions=True)
+ await _cleanup_pidfiles(parent_pidfile, child_pidfile, survivor_pidfile)
diff --git a/tests/tools/test_shell_reap.py b/tests/tools/test_shell_reap.py
index 1ec64a7e2..ba477def9 100644
--- a/tests/tools/test_shell_reap.py
+++ b/tests/tools/test_shell_reap.py
@@ -11,7 +11,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from nanobot.agent.tools.exec_session import _ExecSession
+from nanobot.agent.tools.exec_session import ExecSessionManager, ExecSessionTool, _ExecSession
+from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.agent.tools.shell import ExecTool, _reap_pid
@@ -21,6 +22,50 @@ def _python_command(code: str) -> str:
return f"{shlex.quote(sys.executable)} -u -c {shlex.quote(code)}"
+class _MockProcess:
+ def __init__(
+ self, *, pid: int, returncode: int | None, stdout: bytes = b"", stderr: bytes = b"",
+ ) -> None:
+ self.pid = pid
+ self.returncode = returncode
+ self.stdin = None
+ self.stdout = asyncio.StreamReader()
+ self.stderr = asyncio.StreamReader()
+ self.stdout.feed_data(stdout)
+ self.stderr.feed_data(stderr)
+ self.exited = asyncio.Event()
+ self._exit_code = returncode
+ self.kill = MagicMock(side_effect=lambda: self.exit(-9))
+ self.wait = AsyncMock(side_effect=self._wait)
+ if returncode is not None:
+ self.exit(returncode)
+
+ def exit(self, returncode: int, *, close_streams: bool = True) -> None:
+ self._exit_code = returncode
+ if close_streams:
+ self.stdout.feed_eof()
+ self.stderr.feed_eof()
+ self.exited.set()
+
+ async def _wait(self) -> int:
+ await self.exited.wait()
+ assert self._exit_code is not None
+ self.returncode = self._exit_code
+ return self.returncode
+
+
+async def _cleanup_session(session: _ExecSession) -> None:
+ await asyncio.wait_for(session.kill(), timeout=5)
+ tasks = (
+ session._stdout_task, session._stderr_task, session._completion_task,
+ session._timeout_task, session._kill_task,
+ )
+ await asyncio.wait_for(
+ asyncio.gather(*(task for task in tasks if task is not None), return_exceptions=True),
+ timeout=5,
+ )
+
+
def test_reap_pid_noops_without_waitpid():
"""On platforms (or test stubs) without waitpid, reaping is a no-op."""
with patch("nanobot.agent.tools.shell.os") as mock_os:
@@ -50,9 +95,7 @@ def test_reap_pid_swallows_already_reaped_errors():
@pytest.mark.asyncio
async def test_kill_process_skips_kill_when_already_exited():
"""Already-dead processes must not raise ProcessLookupError from kill()."""
- process = AsyncMock()
- process.pid = 4242
- process.returncode = 0
+ process = _MockProcess(pid=4242, returncode=0)
process.kill = MagicMock(side_effect=ProcessLookupError("already dead"))
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
@@ -65,147 +108,249 @@ async def test_kill_process_skips_kill_when_already_exited():
@pytest.mark.asyncio
async def test_kill_process_kills_and_reaps_live_process():
- process = AsyncMock()
- process.pid = 77
- process.returncode = None
- process.kill = MagicMock()
- process.wait = AsyncMock(return_value=0)
+ process = _MockProcess(pid=77, returncode=None)
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await ExecTool._kill_process(process)
process.kill.assert_called_once()
process.wait.assert_awaited()
+ assert process.returncode == -9
reap.assert_called_once_with(77)
@pytest.mark.asyncio
async def test_kill_process_reaps_even_if_kill_races_exit():
"""If the child exits between returncode check and kill(), still reap."""
- process = AsyncMock()
- process.pid = 88
- process.returncode = None
- process.kill = MagicMock(side_effect=ProcessLookupError("raced exit"))
- process.wait = AsyncMock(return_value=0)
+ process = _MockProcess(pid=88, returncode=None)
+
+ def raced_exit() -> None:
+ process.exit(0)
+ raise ProcessLookupError("raced exit")
+
+ process.kill.side_effect = raced_exit
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await ExecTool._kill_process(process)
process.kill.assert_called_once()
+ process.wait.assert_awaited()
+ assert process.returncode == 0
reap.assert_called_once_with(88)
@pytest.mark.asyncio
async def test_execute_reaps_after_normal_completion():
- mock_proc = AsyncMock()
- mock_proc.pid = 1001
- mock_proc.communicate.return_value = (b"ok\n", b"")
- mock_proc.returncode = 0
-
+ process = _MockProcess(pid=1001, returncode=0, stdout=b"ok\n")
+ manager = ExecSessionManager()
with (
- patch.object(ExecTool, "_spawn", return_value=mock_proc),
- patch.object(ExecTool, "_guard_command", return_value=None),
+ patch.object(ExecTool, "_spawn", return_value=process),
patch("nanobot.agent.tools.shell._reap_pid") as reap,
):
- tool = ExecTool()
- result = await tool.execute(command="echo ok")
+ try:
+ result = await ExecTool(session_manager=manager).execute(command="echo ok")
+ finally:
+ await manager.close_all()
+ assert not is_tool_error_result(result)
assert "ok" in result
assert "Exit code: 0" in result
+ process.wait.assert_awaited()
+ process.kill.assert_not_called()
reap.assert_called_with(1001)
@pytest.mark.asyncio
async def test_execute_timeout_kills_and_reaps():
- mock_proc = AsyncMock()
- mock_proc.pid = 1002
- mock_proc.returncode = None
- mock_proc.communicate.side_effect = asyncio.TimeoutError()
-
+ process = _MockProcess(pid=1002, returncode=None)
+ manager = ExecSessionManager()
with (
- patch.object(ExecTool, "_spawn", return_value=mock_proc) as spawn,
- patch.object(ExecTool, "_guard_command", return_value=None),
- patch.object(ExecTool, "_kill_process_tree", new_callable=AsyncMock) as kill_tree,
+ patch.object(ExecTool, "_spawn", return_value=process) as spawn,
+ patch.object(ExecTool, "_kill_process_tree", side_effect=ExecTool._kill_process) as kill_tree,
+ patch("nanobot.agent.tools.shell._reap_pid") as reap,
):
- tool = ExecTool(timeout=1)
- result = await tool.execute(command="sleep 99", timeout=1)
-
+ try:
+ result = await asyncio.wait_for(
+ ExecTool(timeout=1, session_manager=manager).execute(command="sleep 99", timeout=1),
+ timeout=5,
+ )
+ finally:
+ await manager.close_all()
+
+ assert is_tool_error_result(result)
assert "timed out" in result.lower()
- kill_tree.assert_awaited_once_with(mock_proc)
+ assert "Reason: max_runtime" in result
+ kill_tree.assert_awaited_once_with(process)
+ process.kill.assert_called_once()
+ process.wait.assert_awaited()
+ assert process.returncode == -9
+ reap.assert_any_call(1002)
assert spawn.await_args.kwargs["process_tree"] is True
@pytest.mark.asyncio
async def test_execute_cancellation_kills_process_tree():
- mock_proc = AsyncMock()
- mock_proc.pid = 1005
- mock_proc.returncode = None
- mock_proc.communicate.side_effect = asyncio.CancelledError()
+ process = _MockProcess(pid=1005, returncode=None)
+ manager = ExecSessionManager()
+ waiting = asyncio.Event()
+ wait_exit = _ExecSession.wait_exit
+
+ async def inline_wait(session: _ExecSession) -> None:
+ waiting.set()
+ await wait_exit(session)
with (
- patch.object(ExecTool, "_spawn", return_value=mock_proc) as spawn,
- patch.object(ExecTool, "_guard_command", return_value=None),
- patch.object(ExecTool, "_kill_process_tree", new_callable=AsyncMock) as kill_tree,
+ patch.object(ExecTool, "_spawn", return_value=process) as spawn,
+ patch.object(ExecTool, "_kill_process_tree", side_effect=ExecTool._kill_process) as kill_tree,
+ patch.object(_ExecSession, "wait_exit", new=inline_wait),
+ patch("nanobot.agent.tools.shell._reap_pid") as reap,
):
- with pytest.raises(asyncio.CancelledError):
- await ExecTool().execute(command="sleep 99")
-
- kill_tree.assert_awaited_once_with(mock_proc)
+ execution = asyncio.create_task(
+ ExecTool(session_manager=manager).execute(command="sleep 99"),
+ )
+ try:
+ await asyncio.wait_for(waiting.wait(), timeout=5)
+ assert process.returncode is None
+ execution.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(execution, timeout=5)
+ assert await manager.list() == []
+ finally:
+ execution.cancel()
+ await asyncio.gather(execution, return_exceptions=True)
+ await manager.close_all()
+
+ kill_tree.assert_awaited_once_with(process)
+ process.kill.assert_called_once()
+ process.wait.assert_awaited()
+ assert process.returncode == -9
+ reap.assert_any_call(1005)
assert spawn.await_args.kwargs["process_tree"] is True
@pytest.mark.asyncio
-async def test_execute_exception_after_success_does_not_raise_on_dead_process():
- """Generic except must return ToolResult.error, not ProcessLookupError."""
- mock_proc = AsyncMock()
- mock_proc.pid = 1003
- mock_proc.communicate = AsyncMock(return_value=(b"out\n", b""))
- mock_proc.returncode = 0
- mock_proc.kill = MagicMock(side_effect=ProcessLookupError("already dead"))
+async def test_exec_session_wait_cancellation_does_not_kill_process_tree():
+ process = _MockProcess(pid=1007, returncode=None)
+ manager = ExecSessionManager()
+ session_tool = ExecSessionTool(manager=manager)
+ with (
+ patch.object(ExecTool, "_spawn", return_value=process),
+ patch.object(ExecTool, "_kill_process_tree", side_effect=ExecTool._kill_process) as kill_tree,
+ patch("nanobot.agent.tools.shell._reap_pid") as reap,
+ ):
+ observer = None
+ try:
+ initial = await ExecTool(session_manager=manager).execute(
+ command="sleep 99", yield_time_ms=0,
+ )
+ session_id, session = next(iter(manager._sessions.items()))
+ assert session_id in initial
+ observer = asyncio.create_task(session_tool.execute(
+ session_id=session_id, until_exit=True, timeout_ms=30_000,
+ ))
+ await asyncio.sleep(0)
+ assert not observer.done()
+ observer.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await observer
+
+ assert process.returncode is None
+ assert not session._completion_task.done()
+ process.kill.assert_not_called()
+ kill_tree.assert_not_awaited()
+ assert [info.session_id for info in await manager.list()] == [session_id]
+
+ result = await session_tool.execute(session_id=session_id, terminate=True)
+ assert "Reason: cancelled" in result
+ assert "Exit code: -9" in result
+ finally:
+ if observer is not None:
+ observer.cancel()
+ await asyncio.gather(observer, return_exceptions=True)
+ await manager.close_all()
+
+ kill_tree.assert_awaited_once_with(process)
+ process.kill.assert_called_once()
+ reap.assert_any_call(1007)
+
+async def test_execute_exception_after_success_does_not_raise_on_dead_process():
+ """Formatting a completed result must not attempt to kill the dead process."""
+ process = _MockProcess(pid=1003, returncode=0, stdout=b"out\n")
+ process.kill.side_effect = ProcessLookupError("already dead")
+ manager = ExecSessionManager()
with (
- patch.object(ExecTool, "_spawn", return_value=mock_proc),
- patch.object(ExecTool, "_guard_command", return_value=None),
+ patch.object(ExecTool, "_spawn", return_value=process),
patch("nanobot.agent.tools.shell._reap_pid") as reap,
patch(
- "nanobot.agent.tools.shell.clamp_session_int",
+ "nanobot.agent.tools.shell.format_session_poll",
side_effect=RuntimeError("boom after exit"),
- ),
+ ) as formatter,
):
- tool = ExecTool()
- result = await tool.execute(command="echo out")
+ try:
+ result = await ExecTool(session_manager=manager).execute(command="echo out")
+ finally:
+ await manager.close_all()
+ assert is_tool_error_result(result)
assert "Error executing command" in result
assert "boom after exit" in result
- mock_proc.kill.assert_not_called()
- assert reap.called
+ poll = formatter.call_args.args[1]
+ assert poll.done is True
+ assert poll.exit_code == 0
+ assert poll.output == "out\n"
+ process.wait.assert_awaited()
+ process.kill.assert_not_called()
+ reap.assert_called_with(1003)
@pytest.mark.asyncio
-async def test_execute_exception_during_communicate_kills_live_process():
- mock_proc = AsyncMock()
- mock_proc.pid = 1004
- mock_proc.returncode = None
- mock_proc.communicate.side_effect = OSError("pipe broken")
+async def test_execute_stream_read_error_kills_live_process(tmp_path):
+ manager = ExecSessionManager()
+ tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
+ spawn_process = ExecTool._spawn
+ kill_process_tree = ExecTool._kill_process_tree
+ process = None
+
+ async def spawn_with_broken_stdout(*args, **kwargs):
+ nonlocal process
+ process = await spawn_process(*args, **kwargs)
+ assert process.returncode is None
+ assert process.stdout is not None
+ process.stdout.set_exception(OSError("pipe broken"))
+ return process
with (
- patch.object(ExecTool, "_spawn", return_value=mock_proc),
- patch.object(ExecTool, "_guard_command", return_value=None),
- patch.object(ExecTool, "_kill_process_tree", new_callable=AsyncMock) as kill_tree,
+ patch.object(ExecTool, "_spawn", side_effect=spawn_with_broken_stdout),
+ patch.object(ExecTool, "_kill_process_tree", wraps=kill_process_tree) as kill_tree,
+ patch("nanobot.agent.tools.shell._reap_pid", wraps=_reap_pid) as reap,
):
- tool = ExecTool()
- result = await tool.execute(command="broken")
-
- assert "Error executing command" in result
+ try:
+ result = await asyncio.wait_for(tool.execute(
+ command=[sys.executable, "-u", "-c", "import time; time.sleep(30)"],
+ ), timeout=10)
+ finally:
+ try:
+ await manager.close_all()
+ finally:
+ if process is not None and process.returncode is None:
+ await kill_process_tree(process)
+
+ assert is_tool_error_result(result)
assert "pipe broken" in result
- kill_tree.assert_awaited_once_with(mock_proc)
+ assert "Reason: execution_error" in result
+ assert "output may be incomplete" in result
+ assert "Process running" not in result
+ assert process is not None
+ assert process.returncode is not None and process.returncode != 0
+ kill_tree.assert_awaited_once_with(process)
+ reap.assert_any_call(process.pid)
@pytest.mark.asyncio
async def test_kill_process_tree_targets_group_after_root_exits():
- process = AsyncMock()
- process.pid = 1006
- process.returncode = 0
+ process = _MockProcess(pid=1006, returncode=0)
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
@@ -285,22 +430,9 @@ async def test_kill_process_tree_kills_descendant_after_root_exits(tmp_path):
await ExecTool._kill_process_tree(process)
-def _mock_session_process(*, pid: int, returncode: int | None):
- process = AsyncMock()
- process.pid = pid
- process.returncode = returncode
- process.kill = MagicMock()
- process.wait = AsyncMock(return_value=returncode if returncode is not None else -9)
- # Constructor starts stream readers; closed streams exit immediately.
- process.stdout = None
- process.stderr = None
- process.stdin = None
- return process
-
-
@pytest.mark.asyncio
async def test_exec_session_kill_reaps():
- process = _mock_session_process(pid=2001, returncode=None)
+ process = _MockProcess(pid=2001, returncode=None)
session = _ExecSession(
session_id="abc",
process=process,
@@ -313,15 +445,24 @@ async def test_exec_session_kill_reaps():
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await session.kill()
process.kill.assert_called_once()
- reap.assert_called_once_with(2001)
+ process.wait.assert_awaited()
+ assert process.returncode == -9
+ assert session.finish_reason == "cancelled"
+ assert session.finished_at is not None
+ reap.assert_any_call(2001)
finally:
- await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
+ await _cleanup_session(session)
@pytest.mark.asyncio
async def test_exec_session_kill_reaps_if_process_exits_before_kill():
- process = _mock_session_process(pid=2002, returncode=None)
- process.kill.side_effect = ProcessLookupError("raced exit")
+ process = _MockProcess(pid=2002, returncode=None)
+
+ def raced_exit() -> None:
+ process.exit(0)
+ raise ProcessLookupError("raced exit")
+
+ process.kill.side_effect = raced_exit
session = _ExecSession(
session_id="raced",
process=process,
@@ -333,14 +474,20 @@ async def test_exec_session_kill_reaps_if_process_exits_before_kill():
try:
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await session.kill()
- reap.assert_called_once_with(2002)
+ process.kill.assert_called_once()
+ process.wait.assert_awaited()
+ assert process.returncode == 0
+ assert session.finished_at is not None
+ reap.assert_any_call(2002)
finally:
- await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
+ await _cleanup_session(session)
@pytest.mark.asyncio
async def test_exec_session_kill_waits_for_reader_tasks():
- process = _mock_session_process(pid=2003, returncode=None)
+ process = _MockProcess(pid=2003, returncode=None, stdout=b"head\n")
+ # OS exit can be observed before the readers have consumed the final pipe bytes.
+ process.kill.side_effect = lambda: process.exit(-9, close_streams=False)
session = _ExecSession(
session_id="readers",
process=process,
@@ -349,34 +496,36 @@ async def test_exec_session_kill_waits_for_reader_tasks():
timeout=30,
owner_session_key=None,
)
- await asyncio.gather(session._stdout_task, session._stderr_task)
-
- release = asyncio.Event()
-
- async def reader() -> None:
- await release.wait()
-
- async def wait_for_process() -> int:
- release.set()
- process.returncode = -9
- return -9
-
- session._stdout_task = asyncio.create_task(reader())
- session._stderr_task = asyncio.create_task(reader())
- process.wait = AsyncMock(side_effect=wait_for_process)
+ stopping = asyncio.create_task(session.kill())
try:
- await session.kill()
+ await asyncio.wait_for(process.exited.wait(), timeout=5)
+ await process.wait()
+ done, _ = await asyncio.wait({stopping}, timeout=0.05)
+ assert not done, "kill returned before stdout/stderr reached EOF"
+ assert session.finished_at is None
+
+ process.stdout.feed_data(b"tail\n")
+ process.stderr.feed_data(b"error tail\n")
+ process.stdout.feed_eof()
+ process.stderr.feed_eof()
+ await asyncio.wait_for(stopping, timeout=5)
assert session._stdout_task.done()
assert session._stderr_task.done()
+ poll = await session.poll(yield_time_ms=0, max_output_chars=1000)
+ assert poll.done is True
+ assert poll.output == "head\ntail\n\nSTDERR:\nerror tail\n"
+ assert not poll.output_incomplete
finally:
- release.set()
- await asyncio.gather(session._stdout_task, session._stderr_task)
+ process.stdout.feed_eof()
+ process.stderr.feed_eof()
+ await asyncio.gather(stopping, return_exceptions=True)
+ await _cleanup_session(session)
@pytest.mark.asyncio
async def test_exec_session_poll_reaps_after_exit():
- process = _mock_session_process(pid=2002, returncode=0)
+ process = _MockProcess(pid=2004, returncode=0, stdout=b"hi\n")
session = _ExecSession(
session_id="def",
process=process,
@@ -387,12 +536,16 @@ async def test_exec_session_poll_reaps_after_exit():
)
try:
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
+ await asyncio.wait_for(session.wait_exit(), timeout=5)
poll = await session.poll(yield_time_ms=0, max_output_chars=1000)
assert poll.done is True
assert poll.exit_code == 0
- reap.assert_called_once_with(2002)
+ assert poll.output == "hi\n"
+ assert poll.finish_reason == "exit"
+ process.kill.assert_not_called()
+ reap.assert_called_with(2004)
finally:
- await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
+ await _cleanup_session(session)
@pytest.mark.skipif(sys.platform == "win32", reason="zombie reaping is a Unix waitpid concern")
diff --git a/tests/tools/test_tool_descriptions.py b/tests/tools/test_tool_descriptions.py
index 642b9f59d..1cbecf139 100644
--- a/tests/tools/test_tool_descriptions.py
+++ b/tests/tools/test_tool_descriptions.py
@@ -55,12 +55,23 @@ def test_coding_tool_descriptions_steer_discovery() -> None:
def test_exec_tool_descriptions_are_concise() -> None:
- assert ExecTool().description == "Execute a shell command."
+ exec_description = ExecTool().description
+ assert exec_description.startswith("Execute a shell command.")
+ assert "timeout" in exec_description
+ assert "max_runtime" in exec_description
+ assert "mutually exclusive" in exec_description
+ assert len(exec_description) < 160
assert ExecSessionTool().description == "Manage a session returned by exec."
assert ListExecSessionsTool().description == "List active exec sessions."
exec_parameters = ExecTool().parameters["properties"]
assert "omit to wait for exit" in exec_parameters["yield_time_ms"]["description"]
+ runtime_description = exec_parameters["max_runtime"]["description"].lower()
+ assert "hard" in runtime_description
+ assert "seconds" in runtime_description
+ timeout_description = exec_parameters["timeout"]["description"].lower()
+ assert "alias" in timeout_description
+ assert "max_runtime" in timeout_description
session_parameters = ExecSessionTool().parameters["properties"]
assert set(session_parameters) == {
diff --git a/tests/tools/test_tool_loader.py b/tests/tools/test_tool_loader.py
index 5ae0e7da6..1c62486b3 100644
--- a/tests/tools/test_tool_loader.py
+++ b/tests/tools/test_tool_loader.py
@@ -294,21 +294,24 @@ def test_exec_tool_enabled():
def test_exec_tool_create():
- from nanobot.agent.tools.shell import ExecTool
- mock_config = MagicMock()
- mock_config.exec.enable = True
- mock_config.exec.timeout = 120
- mock_config.exec.sandbox = ""
- mock_config.exec.path_prepend = "/venv/bin"
- mock_config.exec.path_append = ""
- mock_config.exec.allowed_env_keys = []
- mock_config.exec.allow_patterns = []
- mock_config.exec.deny_patterns = []
- mock_config.restrict_to_workspace = False
- ctx = ToolContext(config=mock_config, workspace="/tmp")
+ from nanobot.agent.tools.shell import ExecTool, ExecToolConfig
+ from nanobot.config.schema import ToolsConfig
+
+ config = ToolsConfig(exec=ExecToolConfig(
+ max_runtime=120,
+ max_runtime_limit=900,
+ idle_timeout=15,
+ idle_action="terminate",
+ path_prepend="/venv/bin",
+ ))
+ ctx = ToolContext(config=config, workspace="/tmp")
tool = ExecTool.create(ctx)
+
assert isinstance(tool, ExecTool)
assert tool.path_prepend == "/venv/bin"
+ assert tool._resolve_timeout(None) == 120
+ for name in ("max_runtime", "timeout"):
+ assert tool.parameters["properties"][name]["maximum"] == 900
def test_web_tools_config_cls():
@@ -431,16 +434,10 @@ def test_loader_registers_builtin_tools():
"""Verify the loader produces the same tool set as the old _register_default_tools."""
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
+ from nanobot.agent.tools.shell import ExecToolConfig
mock_config = MagicMock()
- mock_config.exec.enable = True
- mock_config.exec.timeout = 60
- mock_config.exec.sandbox = ""
- mock_config.exec.path_prepend = ""
- mock_config.exec.path_append = ""
- mock_config.exec.allowed_env_keys = []
- mock_config.exec.allow_patterns = []
- mock_config.exec.deny_patterns = []
+ mock_config.exec = ExecToolConfig(max_runtime=60)
mock_config.restrict_to_workspace = False
mock_config.web.enable = True
mock_config.web.search = MagicMock()
diff --git a/tests/tools/test_tool_validation.py b/tests/tools/test_tool_validation.py
index deb983787..0138443b9 100644
--- a/tests/tools/test_tool_validation.py
+++ b/tests/tools/test_tool_validation.py
@@ -1,6 +1,7 @@
import shlex
import subprocess
import sys
+import time
from pathlib import Path
from typing import Any
from unittest.mock import AsyncMock
@@ -912,27 +913,61 @@ async def test_exec_head_tail_truncation(tmp_path) -> None:
assert "Exit code:" in result
-async def test_exec_timeout_parameter() -> None:
- """LLM-supplied timeout should override the constructor default."""
[email protected]("runtime_parameter", ["timeout", "max_runtime"])
+async def test_exec_timeout_parameter(runtime_parameter) -> None:
+ """Both runtime spellings override the constructor's hard budget."""
tool = ExecTool(timeout=60)
- # A very short timeout should cause the command to be killed
- result = await tool.execute(command="sleep 10", timeout=1)
+ started_at = time.monotonic()
+ result = await tool.execute(
+ command=[sys.executable, "-c", "import time; time.sleep(10)"],
+ **{runtime_parameter: 1},
+ )
+
assert "timed out" in result
- assert "1 seconds" in result
+ assert time.monotonic() - started_at < 8
+ assert "Exit code: 0" not in result
+
+
[email protected]("runtime_parameter", ["timeout", "max_runtime"])
[email protected]("runtime", [0, -1, 301])
+async def test_exec_runtime_rejects_out_of_range(
+ monkeypatch, runtime_parameter, runtime,
+) -> None:
+ """Invalid budgets fail before spawning instead of being clamped."""
+ spawn = AsyncMock(side_effect=AssertionError("Invalid runtime must not start a process"))
+ monkeypatch.setattr(ExecTool, "_spawn", spawn)
+ tool = ExecTool(max_runtime=301, max_runtime_limit=300)
+
+ result = await tool.execute(command="echo ok", **{runtime_parameter: runtime})
+
+ assert result.startswith("Error:")
+ assert "runtime" in result or "timeout" in result
+ spawn.assert_not_called()
-async def test_exec_timeout_capped_at_max() -> None:
- """Timeout values above _MAX_TIMEOUT should be clamped."""
+async def test_exec_runtime_aliases_are_mutually_exclusive(monkeypatch) -> None:
+ spawn = AsyncMock(side_effect=AssertionError("Conflicting runtime arguments must not spawn"))
+ monkeypatch.setattr(ExecTool, "_spawn", spawn)
tool = ExecTool()
- # Should not raise — just clamp to 600
- result = await tool.execute(command="echo ok", timeout=9999)
- assert "Exit code: 0" in result
+ params = {"command": "echo ok", "max_runtime": 5, "timeout": 5}
+
+ result = await tool.execute(**params)
+
+ assert result.startswith("Error:")
+ assert "max_runtime" in result
+ assert "timeout" in result
+ spawn.assert_not_called()
-def test_exec_config_timeout_uncapped_and_zero() -> None:
- """Config timeout is no longer capped at 600 and accepts 0 = no limit (#3595)."""
- assert ExecToolConfig(timeout=0).timeout == 0
- assert ExecToolConfig(timeout=3600).timeout == 3600
+def test_exec_config_runtime_defaults_and_timeout_alias() -> None:
+ cfg = ExecToolConfig()
+ assert cfg.max_runtime == 3600
+ assert cfg.max_runtime_limit == 86400
+ assert cfg.idle_timeout == 300
+ assert cfg.idle_action == "report"
+ assert ExecToolConfig(timeout=5).max_runtime == 5
+ assert ExecToolConfig(timeout=3600).max_runtime == 3600
+ assert ExecToolConfig(timeout=0).max_runtime == 0
with pytest.raises(ValidationError):
ExecToolConfig(timeout=-1)
@@ -953,16 +988,38 @@ def test_exec_config_accepts_bwrap_bind_aliases() -> None:
assert dumped["sandboxRwBinds"] == ["/home/user/.cache/uv"]
-def test_resolve_timeout_config_uncapped_and_unlimited() -> None:
- """Config timeout drives the hard timeout uncapped; 0 means no limit (#3595)."""
- assert ExecTool(timeout=3600)._resolve_timeout(None) == 3600
- assert ExecTool(timeout=0)._resolve_timeout(None) is None
-
-
-def test_resolve_timeout_per_call_still_capped() -> None:
- """Per-call (LLM) timeout stays capped at _MAX_TIMEOUT even with unlimited config."""
- assert ExecTool(timeout=0)._resolve_timeout(9999) == ExecTool._MAX_TIMEOUT
- assert ExecTool(timeout=60)._resolve_timeout(120) == 120
+def test_resolve_timeout_uses_configured_hard_budget() -> None:
+ assert ExecTool()._resolve_timeout(None) == 3600
+ assert ExecTool(timeout=5)._resolve_timeout(None) == 5
+ assert ExecTool(max_runtime=172800, max_runtime_limit=60)._resolve_timeout(None) == 172800
+
+
+def test_resolve_timeout_respects_configured_limit_without_clamping() -> None:
+ assert ExecTool()._resolve_timeout(9999) == 9999
+ tool = ExecTool(max_runtime=60, max_runtime_limit=1200)
+ assert tool._resolve_timeout(1) == 1
+ assert tool._resolve_timeout(1200) == 1200
+ for runtime in (0, -1, 1201):
+ with pytest.raises(ValueError):
+ tool._resolve_timeout(runtime)
+
+
[email protected]("limit", [60, 1200, 86400])
[email protected]("runtime_parameter", ["timeout", "max_runtime"])
+def test_exec_runtime_schema_matches_configured_limit(limit, runtime_parameter) -> None:
+ tool = ExecTool(max_runtime=limit + 1, max_runtime_limit=limit)
+ runtime_schema = tool.parameters["properties"][runtime_parameter]
+ assert runtime_schema["minimum"] == 1
+ assert runtime_schema["maximum"] == limit
+ assert tool.validate_params({"command": "echo ok"}) == []
+ for runtime in (1, limit):
+ assert tool.validate_params({"command": "echo ok", runtime_parameter: runtime}) == []
+ for runtime in (0, -1, limit + 1):
+ assert tool.validate_params({"command": "echo ok", runtime_parameter: runtime})
+
+ runtime_schema["maximum"] = 1
+ assert tool.parameters["properties"][runtime_parameter]["maximum"] == limit
+ assert ExecTool().parameters["properties"][runtime_parameter]["maximum"] == 86400
# --- _resolve_type and nullable param tests ---
diff --git a/tests/webui/test_settings_runtime.py b/tests/webui/test_settings_runtime.py
index f72550256..cdc163e4c 100644
--- a/tests/webui/test_settings_runtime.py
+++ b/tests/webui/test_settings_runtime.py
@@ -69,6 +69,7 @@ def test_runtime_patch_persists_and_preserves_other_domains(tmp_path):
{"agents.defaults.max_concurrent_subagents": 0},
{"agents.defaults.max_tool_iterations": True},
{"tools.exec.timeout": -1},
+ {"tools.exec.timeout": 86401},
{"tools.exec.timeout": "60"},
{"tools.exec.enable": "false"},
{"tools.exec.allowed_env_keys": "TOKEN"},
@@ -99,6 +100,39 @@ def test_invalid_patch_is_atomic(tmp_path, values):
assert path.read_bytes() == before
[email protected]("limit", [120, 86400, 172800])
+def test_shell_runtime_editor_uses_the_configured_limit(tmp_path, limit):
+ path = tmp_path / "config.json"
+ config = Config.model_validate({"tools": {"exec": {"maxRuntimeLimit": limit}}})
+ save_config(config, path)
+ before = path.read_bytes()
+
+ with pytest.raises(WebUISettingsError, match=f"1–{limit} seconds"):
+ update_runtime_config_settings({"tools.exec.timeout": limit + 1}, config_path=path)
+ assert path.read_bytes() == before
+
+ payload = update_runtime_config_settings({"tools.exec.timeout": limit}, config_path=path)
+ assert payload["advanced"]["exec_max_runtime_limit"] == limit
+ assert payload["runtime_config"]["tools.exec.timeout"] == limit
+ saved = load_config(path).tools.exec
+ assert saved.max_runtime == limit
+ assert saved.max_runtime_limit == limit
+
+
+def test_other_settings_preserve_a_longer_trusted_shell_runtime(tmp_path):
+ path = tmp_path / "config.json"
+ save_config(Config.model_validate({"tools": {"exec": {
+ "maxRuntime": 172800, "maxRuntimeLimit": 86400,
+ }}}), path)
+
+ update_runtime_config_settings({"tools.exec.path_append": "extra-bin"}, config_path=path)
+
+ saved = load_config(path).tools.exec
+ assert saved.max_runtime == 172800
+ assert saved.max_runtime_limit == 86400
+ assert saved.path_append == "extra-bin"
+
+
def test_remote_client_cannot_change_install_policy():
config = Config()
with pytest.raises(WebUISettingsError) as error:
diff --git a/webui/src/components/settings/system/RuntimeConfigSettings.tsx b/webui/src/components/settings/system/RuntimeConfigSettings.tsx
index c2713c10c..6af847e50 100644
--- a/webui/src/components/settings/system/RuntimeConfigSettings.tsx
+++ b/webui/src/components/settings/system/RuntimeConfigSettings.tsx
@@ -6,6 +6,7 @@ import { SettingsGroup, SettingsRow, SettingsSectionTitle, RestartRequiredNotice
import { ProviderPicker } from "@/components/settings/shared/ModelControls";
import { TimezonePicker } from "@/components/settings/shared/TimezonePicker";
import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor";
+import { ShellRuntimeControl } from "@/components/settings/system/ShellRuntimeControl";
import { Input } from "@/components/ui/input";
import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS, type RuntimeConfigField, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields";
import { updateRuntimeConfigSettings } from "@/lib/api";
@@ -59,6 +60,11 @@ export function useRuntimeConfigSettings(
setErrors((prev) => ({ ...prev, [field.group]: "" }));
setInvalidField(null);
};
+ const reject = (field: RuntimeConfigField, message: string) => {
+ setSaved((prev) => ({ ...prev, [field.group]: false }));
+ setErrors((prev) => ({ ...prev, [field.group]: message }));
+ setInvalidField(field.path);
+ };
const save = async (group: string) => {
if (!settings?.runtime_config) return;
if (saving) {
@@ -70,12 +76,13 @@ export function useRuntimeConfigSettings(
const values: Record<string, RuntimeConfigValue> = {};
for (const field of changed) {
const raw = value(field.path);
- if (field.kind === "number") {
+ if (field.kind === "number" || field.kind === "duration") {
+ const maximum = field.kind === "duration" ? settings.advanced.exec_max_runtime_limit : field.max;
const parsed = Number(raw);
if (String(raw).trim() === "" || !Number.isFinite(parsed)
|| (field.path !== "api.timeout" && !Number.isInteger(parsed))
|| (field.min !== undefined && parsed < field.min)
- || (field.max !== undefined && parsed > field.max)) {
+ || (maximum !== undefined && parsed > maximum)) {
setErrors((prev) => ({ ...prev, [group]: t("settings.runtimeConfig.numberError") }));
setInvalidField(field.path);
return;
@@ -124,7 +131,7 @@ export function useRuntimeConfigSettings(
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
setSaved((prev) => ({ ...prev, [field.group]: true }));
};
- return { value, visible, dirty, discard, change, save, saveList, saving, errors, invalidField, saved };
+ return { value, visible, dirty, discard, change, reject, save, saveList, saving, errors, invalidField, saved };
}
export type RuntimeConfigController = ReturnType<typeof useRuntimeConfigSettings>;
@@ -160,6 +167,7 @@ export function RuntimeConfigSettings({
const dirty = fields.filter(state.visible).some(state.dirty);
const title = tr(`groups.${group.id}.title`);
const errorId = `runtime-error-${group.id}`;
+ const inlineError = fields.some((field) => field.kind === "duration" && state.invalidField === field.path);
const section = (
<section key={group.id} aria-label={title}>
<SettingsSectionTitle>{title}</SettingsSectionTitle>
@@ -195,6 +203,13 @@ export function RuntimeConfigSettings({
<div className="w-full">
{field.path === "agents.defaults.timezone" ? (
<TimezonePicker {...common} value={String(current)} onChange={(next) => state.change(field, next)} />
+ ) : field.kind === "duration" ? (
+ <ShellRuntimeControl value={String(current)} maximum={settings.advanced.exec_max_runtime_limit}
+ controlProps={{ ...common, disabled: disabled || state.saving === group.id || isRestarting }}
+ onChange={(next) => state.change(field, next)}
+ error={state.invalidField === field.path && state.errors[group.id]
+ ? { id: errorId, message: state.errors[group.id] } : undefined}
+ onReject={(message) => state.reject(field, message)} />
) : field.kind === "list" ? (
<SettingsTextEditor id={id} title={text} description={help} value={String(current)}
disabled={disabled || state.saving !== null || isRestarting}
@@ -227,7 +242,7 @@ export function RuntimeConfigSettings({
onRestart={onRestart} isRestarting={isRestarting} />
</SettingsGroup>
</fieldset>
- {state.errors[group.id] ? <p id={errorId} role="alert" className="mt-2 break-words px-1 text-[12px] text-destructive">{state.errors[group.id]}</p> : null}
+ {state.errors[group.id] && !inlineError ? <p id={errorId} role="alert" className="mt-2 break-words px-1 text-[12px] text-destructive">{state.errors[group.id]}</p> : null}
</form>
</section>
);
diff --git a/webui/src/components/settings/system/ShellRuntimeControl.tsx b/webui/src/components/settings/system/ShellRuntimeControl.tsx
new file mode 100644
index 000000000..1f795454f
--- /dev/null
+++ b/webui/src/components/settings/system/ShellRuntimeControl.tsx
@@ -0,0 +1,80 @@
+import { useState, type ComponentProps } from "react";
+import { useTranslation } from "react-i18next";
+
+import { ProviderPicker } from "@/components/settings/shared/ModelControls";
+import { Input } from "@/components/ui/input";
+
+const PRESETS = [900, 1800, 3600, 21600, 43200, 86400];
+
+type ControlProps = Pick<ComponentProps<typeof Input>,
+ "id" | "disabled" | "aria-label" | "aria-describedby" | "aria-invalid">;
+
+function formatDuration(seconds: number, locale: string): string {
+ const [unit, divisor] = seconds % 3600 === 0 ? ["hour", 3600] as const
+ : seconds % 60 === 0 ? ["minute", 60] as const : ["second", 1] as const;
+ return new Intl.NumberFormat(locale, { style: "unit", unit, unitDisplay: "long" }).format(seconds / divisor);
+}
+
+export function ShellRuntimeControl({
+ value, maximum, controlProps, error, onChange, onReject,
+}: {
+ value: string;
+ maximum?: number;
+ controlProps: ControlProps;
+ error?: { id: string; message: string };
+ onChange: (value: string) => void;
+ onReject: (message: string) => void;
+}) {
+ const { t, i18n } = useTranslation();
+ const [customSelected, setCustomSelected] = useState(false);
+ const presets = PRESETS.filter((seconds) => maximum === undefined || seconds <= maximum);
+ if (maximum !== undefined && !presets.includes(maximum)) presets.push(maximum);
+ const custom = customSelected || controlProps["aria-invalid"] === true
+ || (value !== "0" && !presets.includes(Number(value)));
+ const limitId = `${controlProps.id}-limit`;
+ const describedBy = `${controlProps["aria-describedby"] ?? ""}${maximum === undefined ? "" : ` ${limitId}`}`.trim();
+ const unit = new Intl.NumberFormat(i18n.language, {
+ style: "unit", unit: "second", unitDisplay: "short",
+ }).formatToParts(2).find((part) => part.type === "unit")?.value;
+ return (
+ <div className="w-full space-y-1.5">
+ <ProviderPicker
+ triggerProps={{ ...controlProps, id: custom ? `${controlProps.id}-preset` : controlProps.id,
+ "aria-describedby": describedBy }}
+ value={custom ? "custom" : value}
+ emptyLabel={t("settings.runtimeConfig.commandRuntime.custom")}
+ providers={[
+ ...presets.map((seconds) => ({ name: String(seconds), label: formatDuration(seconds, i18n.language) })),
+ { name: "0", label: t("settings.runtimeConfig.commandRuntime.noLimit") },
+ { name: "custom", label: t("settings.runtimeConfig.commandRuntime.custom") },
+ ]}
+ onChange={(next) => {
+ setCustomSelected(next === "custom");
+ if (next !== "custom") onChange(next);
+ }}
+ />
+ {custom ? <div className="relative">
+ <Input {...controlProps} aria-label={t("settings.runtimeConfig.commandRuntime.customLabel")}
+ aria-describedby={describedBy} type="number" inputMode="numeric"
+ min={1} max={maximum} step={1} autoComplete="off" value={value === "0" ? "" : value}
+ className="h-9 rounded-full pr-12 text-[13px] aria-[invalid=true]:border-destructive [&::-webkit-inner-spin-button]:appearance-none"
+ onChange={(event) => {
+ const next = event.target.value;
+ const seconds = Number(next);
+ if (next !== "" && (!Number.isSafeInteger(seconds) || seconds < 1
+ || (maximum !== undefined && seconds > maximum))) {
+ onReject(maximum === undefined ? t("settings.runtimeConfig.numberError")
+ : t("settings.runtimeConfig.commandRuntime.rangeError", { max: maximum.toLocaleString(i18n.language) }));
+ return;
+ }
+ onChange(next);
+ }} />
+ <span aria-hidden className="pointer-events-none absolute inset-y-0 right-3 flex items-center text-[12px] text-muted-foreground">{unit}</span>
+ </div> : null}
+ {maximum !== undefined ? <p id={limitId} className="text-[12px] leading-4 text-muted-foreground">
+ {t("settings.runtimeConfig.commandRuntime.limit", { duration: formatDuration(maximum, i18n.language) })}
+ </p> : null}
+ {error ? <p id={error.id} role="alert" className="text-[12px] leading-4 text-destructive">{error.message}</p> : null}
+ </div>
+ );
+}
diff --git a/webui/src/components/settings/system/runtime-config-fields.ts b/webui/src/components/settings/system/runtime-config-fields.ts
index 9c7479370..b2d45d9bd 100644
--- a/webui/src/components/settings/system/runtime-config-fields.ts
+++ b/webui/src/components/settings/system/runtime-config-fields.ts
@@ -1,7 +1,7 @@
export interface RuntimeConfigField {
group: string;
path: string;
- kind: "toggle" | "text" | "nullable" | "number" | "boolean" | "select" | "list" | "preset";
+ kind: "toggle" | "text" | "nullable" | "number" | "duration" | "boolean" | "select" | "list" | "preset";
options?: string[];
when?: { path: string; value: string | boolean | string[] };
manual?: boolean;
@@ -44,7 +44,7 @@ export const RUNTIME_CONFIG_FIELDS: RuntimeConfigField[] = [
{ group: "web", path: "tools.web.enable", kind: "boolean" },
{ group: "tools", path: "tools.my.enable", kind: "boolean" },
{ group: "tools", path: "tools.my.allow_set", kind: "boolean", when: { path: "tools.my.enable", value: true } },
- { group: "shell", path: "tools.exec.timeout", kind: "number", min: 0 },
+ { group: "shell", path: "tools.exec.timeout", kind: "duration", min: 0 },
{ group: "shell", path: "tools.exec.path_prepend", kind: "text" },
{ group: "shell", path: "tools.exec.path_append", kind: "text" },
{ group: "shell", path: "tools.exec.sandbox", kind: "select", options: ["", "bwrap", "seatbelt"] },
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index c1f7e68a8..27d2b411f 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "Saved. Restart the API service to apply changes.",
+ "commandRuntime": {
+ "custom": "Custom (seconds)",
+ "customLabel": "Custom runtime (seconds)",
+ "noLimit": "No time limit",
+ "limit": "Timed runs: up to {{duration}}",
+ "rangeError": "Enter whole seconds from 1 to {{max}}, or choose No time limit."
+ },
"fields": {
"agents_defaults_timezone_mode": {
"label": "System timezone",
@@ -465,8 +472,8 @@
"help": "Allow the agent to change its configuration.\n\nAllow the self-management tool to update configuration."
},
"tools_exec_timeout": {
- "label": "Command timeout",
- "help": "Stop commands after this many seconds; 0 means unlimited.\n\nStop commands that exceed this duration. Set to 0 for no time limit."
+ "label": "Command runtime",
+ "help": "Default hard runtime limit for shell commands.\n\nOutput and waiting do not extend it. Choose No time limit to remove this limit."
},
"tools_exec_path_prepend": {
"label": "PATH priority",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index baf2b0171..ccf1f7528 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "Guardado. Reinicia el servicio API para aplicar los cambios.",
+ "commandRuntime": {
+ "custom": "Personalizada (segundos)",
+ "customLabel": "Duración personalizada (segundos)",
+ "noLimit": "Sin límite de tiempo",
+ "limit": "Con límite: hasta {{duration}}",
+ "rangeError": "Introduce un número entero de segundos entre 1 y {{max}}, o elige Sin límite de tiempo."
+ },
"fields": {
"agents_defaults_timezone_mode": {"label": "Zona del sistema", "help": "Desactívalo para elegir una zona horaria.\n\nDesactiva esta opción para elegir la zona horaria manualmente."},
"agents_defaults_timezone": {"label": "Zona horaria", "help": "Los desfases UTC usan la fecha actual.\n\nElige una zona horaria. La diferencia con UTC corresponde a la fecha actual."},
@@ -410,7 +417,7 @@
"tools_cli_apps_enable": {"label": "Apps CLI", "help": "Permite instalar, gestionar y ejecutar apps CLI.\n\nPermite al agente gestionar y ejecutar aplicaciones de línea de comandos."},
"tools_my_enable": {"label": "Ver configuración", "help": "Permite al agente consultar su configuración."},
"tools_my_allow_set": {"label": "Editar configuración", "help": "Permite al agente cambiar su configuración.\n\nPermite que la herramienta de autogestión modifique la configuración."},
- "tools_exec_timeout": {"label": "Tiempo límite de comandos", "help": "Detén los comandos tras estos segundos; 0 significa sin límite.\n\nDuración máxima de un comando de shell. 0 significa sin límite."},
+ "tools_exec_timeout": {"label": "Duración de los comandos", "help": "Límite de duración predeterminado para los comandos de shell.\n\nLa salida y la espera no amplían este límite. Elige Sin límite de tiempo para eliminar el límite de duración."},
"tools_exec_path_prepend": {"label": "Prioridad de PATH", "help": "Busca primero en estos directorios.\n\nDirectorios que se añaden al inicio de PATH. Sepáralos con punto y coma en Windows o con dos puntos en macOS y Linux."},
"tools_exec_path_append": {"label": "Añadidos a PATH", "help": "Busca al final en estos directorios.\n\nDirectorios que se añaden al final de PATH. Sepáralos con punto y coma en Windows o con dos puntos en macOS y Linux."},
"tools_exec_sandbox": {"label": "Sandbox de comandos", "help": "Aísla los procesos de comandos; requiere soporte del sistema.\n\nUsa bwrap en Linux o Seatbelt en macOS. Las comprobaciones del espacio de trabajo por sí solas no aíslan los procesos."},
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index 042865c44..4ab330ebb 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "Enregistré. Redémarrez le service API pour appliquer les modifications.",
+ "commandRuntime": {
+ "custom": "Personnalisée (secondes)",
+ "customLabel": "Durée personnalisée (secondes)",
+ "noLimit": "Sans limite de temps",
+ "limit": "Durée limitée : jusqu’à {{duration}}",
+ "rangeError": "Saisissez un nombre entier de secondes entre 1 et {{max}}, ou choisissez Sans limite de temps."
+ },
"fields": {
"agents_defaults_timezone_mode": {"label": "Fuseau système", "help": "Désactivez pour choisir un fuseau horaire.\n\nDésactivez pour choisir le fuseau horaire manuellement."},
"agents_defaults_timezone": {"label": "Fuseau horaire", "help": "Les décalages UTC utilisent la date actuelle.\n\nChoisissez un fuseau horaire. Le décalage UTC correspond à la date actuelle."},
@@ -410,7 +417,7 @@
"tools_cli_apps_enable": {"label": "Applications CLI", "help": "Autorisez l’installation, la gestion et l’exécution d’applications CLI.\n\nAutorise l’agent à gérer et à exécuter ces applications."},
"tools_my_enable": {"label": "Voir la configuration", "help": "Autorisez l’agent à consulter sa configuration.\n\nAutorise l’agent à consulter sa configuration."},
"tools_my_allow_set": {"label": "Modifier la configuration", "help": "Autorisez l’agent à modifier sa configuration.\n\nAutorise l’outil d’autogestion à modifier la configuration."},
- "tools_exec_timeout": {"label": "Délai des commandes", "help": "Arrêtez les commandes après ce nombre de secondes ; 0 signifie sans limite.\n\nDurée maximale d’une commande shell. 0 signifie aucune limite."},
+ "tools_exec_timeout": {"label": "Durée des commandes", "help": "Durée maximale par défaut des commandes shell.\n\nNi la sortie des commandes ni l’attente ne prolongent cette limite. Choisissez Sans limite de temps pour supprimer la limite de durée."},
"tools_exec_path_prepend": {"label": "Priorité PATH", "help": "Recherchez d’abord dans ces dossiers.\n\nDossiers à placer au début de PATH. Séparez-les par un point-virgule sous Windows ou par deux-points sous macOS et Linux."},
"tools_exec_path_append": {"label": "Ajouts au PATH", "help": "Recherchez dans ces dossiers en dernier.\n\nDossiers à placer à la fin de PATH. Séparez-les par un point-virgule sous Windows ou par deux-points sous macOS et Linux."},
"tools_exec_sandbox": {"label": "Bac à sable des commandes", "help": "Isolez les processus de commande ; nécessite une prise en charge système.\n\nUtilisez bwrap sous Linux ou Seatbelt sous macOS. Les contrôles de l’espace de travail seuls n’isolent pas les processus."},
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index 09d81d1d5..f2f3bfd73 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "Tersimpan. Mulai ulang layanan API untuk menerapkan perubahan.",
+ "commandRuntime": {
+ "custom": "Kustom (detik)",
+ "customLabel": "Durasi kustom (detik)",
+ "noLimit": "Tanpa batas waktu",
+ "limit": "Dengan batas waktu: hingga {{duration}}",
+ "rangeError": "Masukkan jumlah detik berupa bilangan bulat dari 1 hingga {{max}}, atau pilih Tanpa batas waktu."
+ },
"fields": {
"agents_defaults_timezone_mode": {"label": "Zona waktu sistem", "help": "Nonaktifkan untuk memilih zona waktu.\n\nNonaktifkan untuk memilih zona waktu secara manual."},
"agents_defaults_timezone": {"label": "Zona waktu", "help": "Selisih UTC mengikuti tanggal saat ini.\n\nPilih zona waktu. Selisih waktu dari UTC mengikuti tanggal saat ini."},
@@ -410,7 +417,7 @@
"tools_cli_apps_enable": {"label": "Aplikasi CLI", "help": "Izinkan pemasangan, pengelolaan, dan menjalankan aplikasi CLI.\n\nMengizinkan agen mengelola dan menjalankan aplikasi baris perintah."},
"tools_my_enable": {"label": "Lihat konfigurasi", "help": "Izinkan agen melihat konfigurasinya.\n\nMengizinkan agen memeriksa konfigurasinya sendiri."},
"tools_my_allow_set": {"label": "Ubah konfigurasi", "help": "Izinkan agen mengubah konfigurasinya.\n\nMengizinkan alat pengelolaan diri memperbarui konfigurasi."},
- "tools_exec_timeout": {"label": "Batas waktu perintah", "help": "Hentikan perintah setelah jumlah detik ini; 0 berarti tanpa batas.\n\nDurasi maksimum perintah shell. 0 berarti tanpa batas."},
+ "tools_exec_timeout": {"label": "Durasi perintah", "help": "Batas durasi bawaan untuk perintah shell.\n\nKeluaran dan waktu tunggu tidak memperpanjang batas ini. Pilih Tanpa batas waktu untuk menghapus batas durasi."},
"tools_exec_path_prepend": {"label": "Prioritas PATH", "help": "Cari di direktori ini terlebih dahulu.\n\nDirektori yang ditambahkan di awal PATH. Pisahkan dengan titik koma di Windows atau titik dua di macOS dan Linux."},
"tools_exec_path_append": {"label": "Tambahan PATH", "help": "Cari di direktori ini terakhir.\n\nDirektori yang ditambahkan di akhir PATH. Pisahkan dengan titik koma di Windows atau titik dua di macOS dan Linux."},
"tools_exec_sandbox": {"label": "Sandbox perintah", "help": "Isolasi proses perintah; memerlukan dukungan sistem.\n\nGunakan bwrap di Linux atau Seatbelt di macOS. Pemeriksaan ruang kerja saja tidak mengisolasi proses."},
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 59256a09d..81206ead0 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "保存しました。API サービスを再起動すると反映されます。",
+ "commandRuntime": {
+ "custom": "カスタム(秒)",
+ "customLabel": "カスタム実行時間(秒)",
+ "noLimit": "時間制限なし",
+ "limit": "時間制限あり:最大 {{duration}}",
+ "rangeError": "1 から {{max}} までの整数で秒数を入力するか、「時間制限なし」を選んでください。"
+ },
"fields": {
"agents_defaults_timezone_mode": {"label": "システムの時間帯", "help": "オフにすると時間帯を指定できます。\n\nオフにすると手動でタイムゾーンを選択できます。"},
"agents_defaults_timezone": {"label": "タイムゾーン", "help": "UTC オフセットは今日の日付に基づきます。\n\nタイムゾーンを選択します。UTC との時差は現在の日付に基づきます。"},
@@ -410,7 +417,7 @@
"tools_cli_apps_enable": {"label": "CLI アプリ", "help": "CLI アプリのインストール・管理・実行を許可します。\n\nエージェントによる CLI アプリの管理と実行を許可します。"},
"tools_my_enable": {"label": "設定を確認", "help": "エージェントによる自身の設定の確認を許可します。\n\nエージェントが自身の設定を確認できるようにします。"},
"tools_my_allow_set": {"label": "設定を変更", "help": "エージェントによる自身の設定の変更を許可します。\n\n自己管理ツールによる設定の更新を許可します。"},
- "tools_exec_timeout": {"label": "コマンドの制限時間", "help": "この秒数でコマンドを停止します。0 は無制限です。\n\nシェルコマンドの実行時間の上限。0 は無制限です。"},
+ "tools_exec_timeout": {"label": "コマンドの実行時間", "help": "シェルコマンドの既定の実行時間上限です。\n\n出力や待機によって上限は延長されません。「時間制限なし」を選ぶと実行時間の上限がなくなります。"},
"tools_exec_path_prepend": {"label": "PATH の優先検索", "help": "これらのディレクトリを先に検索します。\n\nPATH の先頭に追加するディレクトリです。Windows ではセミコロン、macOS と Linux ではコロンで区切ります。"},
"tools_exec_path_append": {"label": "PATH の末尾追加", "help": "これらのディレクトリを最後に検索します。\n\nPATH の末尾に追加するディレクトリです。Windows ではセミコロン、macOS と Linux ではコロンで区切ります。"},
"tools_exec_sandbox": {"label": "コマンドサンドボックス", "help": "コマンドのプロセスを隔離します。システムの対応が必要です。\n\nLinux では bwrap、macOS では Seatbelt を使用します。ワークスペースの検査だけではプロセスは隔離されません。"},
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index afc5c4049..860e9dcea 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "저장했습니다. API 서비스를 다시 시작하면 적용됩니다.",
+ "commandRuntime": {
+ "custom": "사용자 지정(초)",
+ "customLabel": "사용자 지정 실행 시간(초)",
+ "noLimit": "시간 제한 없음",
+ "limit": "제한 시간: 최대 {{duration}}",
+ "rangeError": "1~{{max}} 사이의 정수(초)를 입력하거나 ‘시간 제한 없음’을 선택하세요."
+ },
"fields": {
"agents_defaults_timezone_mode": {"label": "시스템 시간대", "help": "끄면 시간대를 직접 선택할 수 있습니다."},
"agents_defaults_timezone": {"label": "시간대", "help": "UTC 오프셋은 오늘 날짜를 기준으로 합니다.\n\n시간대를 선택하세요. UTC 시차는 현재 날짜를 기준으로 표시됩니다."},
@@ -410,7 +417,7 @@
"tools_cli_apps_enable": {"label": "CLI 앱", "help": "CLI 앱 설치, 관리 및 실행을 허용합니다.\n\n에이전트의 CLI 앱 관리와 실행을 허용합니다."},
"tools_my_enable": {"label": "설정 확인", "help": "에이전트가 자신의 설정을 확인하도록 허용합니다."},
"tools_my_allow_set": {"label": "설정 변경", "help": "에이전트가 자신의 설정을 변경하도록 허용합니다.\n\n자체 관리 도구의 설정 수정을 허용합니다."},
- "tools_exec_timeout": {"label": "명령 제한 시간", "help": "지정한 초가 지나면 명령을 멈춥니다. 0은 무제한입니다.\n\n셸 명령의 최대 실행 시간입니다. 0은 무제한입니다."},
+ "tools_exec_timeout": {"label": "명령 실행 시간", "help": "셸 명령에 기본으로 적용되는 최대 실행 시간입니다.\n\n출력이나 대기로 이 제한이 늘어나지 않습니다. ‘시간 제한 없음’을 선택하면 실행 시간 제한이 해제됩니다."},
"tools_exec_path_prepend": {"label": "PATH 우선 검색", "help": "이 디렉터리부터 검색합니다.\n\nPATH 앞에 추가할 디렉터리입니다. Windows에서는 세미콜론, macOS와 Linux에서는 콜론으로 구분하세요."},
"tools_exec_path_append": {"label": "PATH 추가 검색", "help": "이 디렉터리를 마지막에 검색합니다.\n\nPATH 뒤에 추가할 디렉터리입니다. Windows에서는 세미콜론, macOS와 Linux에서는 콜론으로 구분하세요."},
"tools_exec_sandbox": {"label": "명령 샌드박스", "help": "명령 프로세스를 격리합니다. 시스템 지원이 필요합니다.\n\nLinux에서는 bwrap, macOS에서는 Seatbelt를 사용합니다. 작업 공간 검사만으로는 프로세스가 격리되지 않습니다."},
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index b7d234ff3..a0ce4cfc6 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "Salvo. Reinicie o serviço de API para aplicar as alterações.",
+ "commandRuntime": {
+ "custom": "Personalizada (segundos)",
+ "customLabel": "Duração personalizada (segundos)",
+ "noLimit": "Sem limite de tempo",
+ "limit": "Com limite: até {{duration}}",
+ "rangeError": "Digite um número inteiro de segundos de 1 a {{max}}, ou escolha Sem limite de tempo."
+ },
"fields": {
"agents_defaults_timezone_mode": {"label": "Fuso do sistema", "help": "Desative para escolher um fuso horário.\n\nDesative para escolher o fuso horário manualmente."},
"agents_defaults_timezone": {"label": "Fuso horário", "help": "Os deslocamentos UTC usam a data atual.\n\nEscolha um fuso horário. A diferença em relação ao UTC considera a data atual."},
@@ -410,7 +417,7 @@
"tools_cli_apps_enable": {"label": "Apps CLI", "help": "Permita instalar, gerenciar e executar apps CLI.\n\nPermite que o agente gerencie e execute aplicativos de linha de comando."},
"tools_my_enable": {"label": "Ver configuração", "help": "Permita que o agente consulte sua configuração.\n\nPermite que o agente consulte sua própria configuração."},
"tools_my_allow_set": {"label": "Editar configuração", "help": "Permita que o agente altere sua configuração.\n\nPermite que a ferramenta de autogerenciamento atualize a configuração."},
- "tools_exec_timeout": {"label": "Tempo limite de comandos", "help": "Pare os comandos após este número de segundos; 0 significa sem limite.\n\nDuração máxima dos comandos de shell. 0 significa sem limite."},
+ "tools_exec_timeout": {"label": "Duração dos comandos", "help": "Limite padrão de duração dos comandos de shell.\n\nA saída e a espera não prolongam esse limite. Escolha Sem limite de tempo para remover o limite de duração."},
"tools_exec_path_prepend": {"label": "Prioridade no PATH", "help": "Pesquise primeiro nestas pastas.\n\nDiretórios adicionados ao início de PATH. Separe-os com ponto e vírgula no Windows ou com dois-pontos no macOS e no Linux."},
"tools_exec_path_append": {"label": "Adições ao PATH", "help": "Pesquise nestas pastas por último.\n\nDiretórios adicionados ao final de PATH. Separe-os com ponto e vírgula no Windows ou com dois-pontos no macOS e no Linux."},
"tools_exec_sandbox": {"label": "Sandbox de comandos", "help": "Isole os processos de comandos; requer suporte do sistema.\n\nUse bwrap no Linux ou Seatbelt no macOS. As verificações do espaço de trabalho, por si só, não isolam processos."},
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index 928788d66..4fc1c9a8b 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "Đã lưu. Khởi động lại dịch vụ API để áp dụng thay đổi.",
+ "commandRuntime": {
+ "custom": "Tùy chỉnh (giây)",
+ "customLabel": "Thời gian chạy tùy chỉnh (giây)",
+ "noLimit": "Không giới hạn thời gian",
+ "limit": "Có giới hạn: tối đa {{duration}}",
+ "rangeError": "Nhập số giây nguyên từ 1 đến {{max}}, hoặc chọn Không giới hạn thời gian."
+ },
"fields": {
"agents_defaults_timezone_mode": {"label": "Múi giờ hệ thống", "help": "Tắt để chọn múi giờ.\n\nTắt để chọn múi giờ thủ công."},
"agents_defaults_timezone": {"label": "Múi giờ", "help": "Độ lệch UTC theo ngày hiện tại.\n\nChọn múi giờ. Độ lệch UTC được tính theo ngày hiện tại."},
@@ -410,7 +417,7 @@
"tools_cli_apps_enable": {"label": "Ứng dụng CLI", "help": "Cho phép cài đặt, quản lý và chạy ứng dụng CLI.\n\nCho phép tác nhân quản lý và chạy ứng dụng dòng lệnh."},
"tools_my_enable": {"label": "Xem cấu hình", "help": "Cho phép agent xem cấu hình của mình.\n\nCho phép tác nhân xem cấu hình của mình."},
"tools_my_allow_set": {"label": "Sửa cấu hình", "help": "Cho phép agent thay đổi cấu hình của mình.\n\nCho phép công cụ tự quản lý cập nhật cấu hình."},
- "tools_exec_timeout": {"label": "Thời hạn lệnh", "help": "Dừng lệnh sau số giây này; 0 là không giới hạn.\n\nThời gian chạy tối đa của lệnh shell. 0 nghĩa là không giới hạn."},
+ "tools_exec_timeout": {"label": "Thời gian chạy lệnh", "help": "Giới hạn thời gian chạy mặc định cho lệnh shell.\n\nĐầu ra và việc chờ đợi không kéo dài giới hạn này. Chọn Không giới hạn thời gian để bỏ giới hạn thời gian chạy."},
"tools_exec_path_prepend": {"label": "Ưu tiên PATH", "help": "Tìm trong các thư mục này trước.\n\nCác thư mục thêm vào đầu PATH. Phân cách bằng dấu chấm phẩy trên Windows hoặc dấu hai chấm trên macOS và Linux."},
"tools_exec_path_append": {"label": "Bổ sung PATH", "help": "Tìm trong các thư mục này sau cùng.\n\nCác thư mục thêm vào cuối PATH. Phân cách bằng dấu chấm phẩy trên Windows hoặc dấu hai chấm trên macOS và Linux."},
"tools_exec_sandbox": {"label": "Hộp cát lệnh", "help": "Cô lập tiến trình lệnh; cần hệ thống hỗ trợ.\n\nDùng bwrap trên Linux hoặc Seatbelt trên macOS. Chỉ kiểm tra không gian làm việc không thể cô lập tiến trình."},
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index 6ccceb41c..6b0dfa6dd 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "已保存,重启 API 服务后生效。",
+ "commandRuntime": {
+ "custom": "自定义(秒)",
+ "customLabel": "自定义运行时长(秒)",
+ "noLimit": "不限时",
+ "limit": "限时最长 {{duration}}",
+ "rangeError": "请输入 1 到 {{max}} 之间的整数秒,或选择“不限时”。"
+ },
"fields": {
"agents_defaults_timezone_mode": {
"label": "系统时区",
@@ -465,8 +472,8 @@
"help": "允许智能体修改自身配置"
},
"tools_exec_timeout": {
- "label": "执行超时",
- "help": "执行超时即停止;0 为不限,单位秒\n\n超过此时长后终止命令。设为 0 表示不限制执行时长。"
+ "label": "运行上限",
+ "help": "Shell 命令的默认运行上限\n\n命令输出或继续等待都不会延长此上限。选择“不限时”可取消运行时限。"
},
"tools_exec_path_prepend": {
"label": "优先目录",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index a776cf1a3..d8876dcff 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -391,6 +391,13 @@
},
"runtimeConfig": {
"apiSaved": "已儲存,重新啟動 API 服務後生效。",
+ "commandRuntime": {
+ "custom": "自訂(秒)",
+ "customLabel": "自訂執行時間(秒)",
+ "noLimit": "不限時",
+ "limit": "限時最長 {{duration}}",
+ "rangeError": "請輸入 1 到 {{max}} 之間的整數秒,或選擇「不限時」。"
+ },
"fields": {
"agents_defaults_timezone_mode": {"label": "系統時區", "help": "關閉後可手動指定時區"},
"agents_defaults_timezone": {"label": "時區", "help": "UTC 偏移按當前日期顯示"},
@@ -410,7 +417,7 @@
"tools_cli_apps_enable": {"label": "CLI 應用", "help": "允許安裝、管理和執行 CLI 應用"},
"tools_my_enable": {"label": "檢視配置", "help": "允許智慧體檢視自身配置"},
"tools_my_allow_set": {"label": "修改配置", "help": "允許智慧體修改自身配置"},
- "tools_exec_timeout": {"label": "執行超時", "help": "執行超時即停止;0 為不限,單位秒\n\n超過此時長後終止命令。設為 0 表示不限制執行時長。"},
+ "tools_exec_timeout": {"label": "執行上限", "help": "Shell 命令的預設執行上限\n\n命令輸出或繼續等待都不會延長此上限。選擇「不限時」可取消執行時限。"},
"tools_exec_path_prepend": {"label": "優先目錄", "help": "優先查詢命令的目錄\n\n新增到 PATH 開頭。多個目錄在 Windows 上用分號分隔,在 Linux 和 macOS 上用冒號分隔。"},
"tools_exec_path_append": {"label": "追加目錄", "help": "最後查詢命令的目錄\n\n新增到 PATH 末尾。多個目錄在 Windows 上用分號分隔,在 Linux 和 macOS 上用冒號分隔。"},
"tools_exec_sandbox": {"label": "命令沙箱", "help": "隔離命令程序,需系統支援\n\nLinux 使用 bwrap,macOS 使用 Seatbelt。工作區路徑限制本身不提供程序隔離。"},
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index e64c08262..72772a570 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -957,6 +957,7 @@ export interface SettingsPayload {
private_service_protection_enabled: boolean;
mcp_server_count: number;
exec_enabled: boolean;
+ exec_max_runtime_limit?: number;
exec_sandbox?: string | null;
exec_path_prepend_set: boolean;
exec_path_append_set: boolean;
diff --git a/webui/src/tests/settings-runtime-config.test.tsx b/webui/src/tests/settings-runtime-config.test.tsx
index 702dea497..7818a30fd 100644
--- a/webui/src/tests/settings-runtime-config.test.tsx
+++ b/webui/src/tests/settings-runtime-config.test.tsx
@@ -6,7 +6,8 @@ import { DEFAULT_AGENT_SETTINGS_DRAFT } from "@/components/settings/models/Model
import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";
function runtimeSettings() {
- return { ...settingsPayload(), runtime_config: {
+ const payload = settingsPayload();
+ return { ...payload, advanced: { ...payload.advanced, exec_max_runtime_limit: 86400 }, runtime_config: {
"agents.defaults.bot_name": "nanobot",
"agents.defaults.bot_icon": "🐈",
"agents.defaults.timezone_mode": "auto",
@@ -142,7 +143,7 @@ describe("Runtime configuration settings", () => {
requestMutationMock.mockResolvedValue({ ...payload, requires_restart: true,
runtime_config: { ...payload.runtime_config, "tools.exec.timeout": 90 } });
renderSettingsView({ initialSection: "advanced", initialSettings: payload });
- fireEvent.change(screen.getByRole("spinbutton", { name: "Command timeout" }), { target: { value: "90" } });
+ fireEvent.change(screen.getByRole("spinbutton", { name: "Custom runtime (seconds)" }), { target: { value: "90" } });
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.runtime_config.update", { values: { "tools.exec.timeout": 90 } }, 20_000,
));
@@ -152,7 +153,7 @@ describe("Runtime configuration settings", () => {
it("validates numbers and keeps a failed draft editable", async () => {
requestMutationMock.mockRejectedValue(new Error("Could not save settings"));
renderSettingsView({ initialSection: "advanced", initialSettings: runtimeSettings() });
- const field = screen.getByRole("spinbutton", { name: "Command timeout" });
+ const field = screen.getByRole("spinbutton", { name: "Custom runtime (seconds)" });
fireEvent.change(field, { target: { value: "-1" } });
await waitFor(() => expect(field).toHaveFocus());
expect(field).toHaveAttribute("aria-invalid", "true");
@@ -162,6 +163,104 @@ describe("Runtime configuration settings", () => {
expect(field).toHaveValue(17);
});
+ it.each([
+ ["24 hours", 86400],
+ ["No time limit", 0],
+ ])("saves the %s command runtime preset in seconds", async (label, seconds) => {
+ const payload = runtimeSettings();
+ payload.runtime_config["tools.exec.timeout"] = 3600;
+ requestMutationMock.mockResolvedValue({ ...payload, runtime_config: {
+ ...payload.runtime_config, "tools.exec.timeout": seconds,
+ } });
+ renderSettingsView({ initialSection: "advanced", initialSettings: payload });
+
+ const control = screen.getByRole("combobox", { name: "Command runtime" });
+ expect(control).toHaveTextContent("1 hour");
+ expect(screen.getByText("Timed runs: up to 24 hours")).toBeVisible();
+ fireEvent.click(control);
+ fireEvent.click(screen.getByRole("option", { name: label, exact: true }));
+
+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.runtime_config.update", { values: { "tools.exec.timeout": seconds } }, 20_000,
+ ));
+ });
+
+ it("rejects over-limit custom input without clamping or saving it", async () => {
+ const payload = runtimeSettings();
+ payload.runtime_config["tools.exec.timeout"] = 3600;
+ requestMutationMock.mockResolvedValue({ ...payload, runtime_config: {
+ ...payload.runtime_config, "tools.exec.timeout": 86400,
+ } });
+ renderSettingsView({ initialSection: "advanced", initialSettings: payload });
+ fireEvent.click(screen.getByRole("combobox", { name: "Command runtime" }));
+ fireEvent.click(screen.getByRole("option", { name: "Custom (seconds)", exact: true }));
+ const field = screen.getByRole("spinbutton", { name: "Custom runtime (seconds)" });
+ expect(field).toHaveAttribute("max", "86400");
+ fireEvent.change(field, { target: { value: "86401" } });
+
+ expect(field).toHaveValue(3600);
+ expect(field).toHaveAttribute("aria-invalid", "true");
+ expect(screen.getByRole("alert")).toHaveTextContent("1 to 86,400");
+ expect(requestMutationMock).not.toHaveBeenCalled();
+
+ fireEvent.change(field, { target: { value: "86400" } });
+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.runtime_config.update", { values: { "tools.exec.timeout": 86400 } }, 20_000,
+ ));
+ await screen.findByText("Saved.", { exact: true });
+ fireEvent.change(field, { target: { value: "86401" } });
+ expect(field).toHaveValue(86400);
+ expect(screen.getAllByRole("alert")).toHaveLength(1);
+ expect(screen.queryByText("Saved.", { exact: true })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "System", exact: true }));
+ fireEvent.click(screen.getByRole("button", { name: "Advanced", exact: true }));
+ expect(screen.getByRole("spinbutton", { name: "Custom runtime (seconds)" })).toHaveValue(86400);
+ expect(screen.getByRole("alert")).toHaveTextContent("1 to 86,400");
+ });
+
+ it("starts a custom duration from No time limit without saving an empty value", async () => {
+ const payload = runtimeSettings();
+ payload.runtime_config["tools.exec.timeout"] = 0;
+ requestMutationMock.mockResolvedValue({ ...payload, runtime_config: {
+ ...payload.runtime_config, "tools.exec.timeout": 120,
+ } });
+ renderSettingsView({ initialSection: "advanced", initialSettings: payload });
+ fireEvent.click(screen.getByRole("combobox", { name: "Command runtime" }));
+ fireEvent.click(screen.getByRole("option", { name: "Custom (seconds)", exact: true }));
+ const field = screen.getByRole("spinbutton", { name: "Custom runtime (seconds)" });
+ expect(field).toHaveValue(null);
+ expect(requestMutationMock).not.toHaveBeenCalled();
+ fireEvent.change(field, { target: { value: "120" } });
+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.runtime_config.update", { values: { "tools.exec.timeout": 120 } }, 20_000,
+ ));
+ });
+
+ it("uses the gateway's configured runtime limit for presets and custom input", () => {
+ const payload = runtimeSettings();
+ payload.advanced.exec_max_runtime_limit = 7200;
+ renderSettingsView({ initialSection: "advanced", initialSettings: payload });
+ expect(screen.getByText("Timed runs: up to 2 hours")).toBeVisible();
+ expect(screen.getByRole("spinbutton", { name: "Custom runtime (seconds)" })).toHaveAttribute("max", "7200");
+ fireEvent.click(screen.getByRole("combobox", { name: "Command runtime" }));
+ expect(screen.getByRole("option", { name: "2 hours", exact: true })).toBeVisible();
+ expect(screen.queryByRole("option", { name: "24 hours", exact: true })).not.toBeInTheDocument();
+ });
+
+ it("keeps runtime editing available on a host without limit metadata", async () => {
+ const payload = runtimeSettings();
+ requestMutationMock.mockResolvedValue({ ...payload, runtime_config: {
+ ...payload.runtime_config, "tools.exec.timeout": 90,
+ } });
+ renderSettingsView({ initialSection: "advanced", initialSettings: {
+ ...payload, advanced: settingsPayload().advanced,
+ } });
+ fireEvent.change(screen.getByRole("spinbutton", { name: "Custom runtime (seconds)" }), { target: { value: "90" } });
+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.runtime_config.update", { values: { "tools.exec.timeout": 90 } }, 20_000,
+ ));
+ });
+
it("preserves drafts when navigating away and supports explicit clearing", async () => {
renderSettingsView({ initialSection: "capabilities", initialSettings: runtimeSettings() });
const openWebSettings = () => {