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

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

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

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

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

No files matched your search

+339 -166
View File
@@ -10,7 +10,7 @@ import uuid
from collections import deque
from contextlib import suppress
from dataclasses import dataclass
from typing import Any
from typing import Any, Literal
from loguru import logger
@@ -36,7 +36,11 @@ DEFAULT_UNTIL_EXIT_MS = 600_000
MAX_WAIT_FOR_MS = 600_000
DEFAULT_MAX_OUTPUT_CHARS = 10_000
MAX_OUTPUT_CHARS = 50_000
OUTPUT_DRAIN_GRACE_S = 0.1
FinishReason = Literal[
"exit", "max_runtime", "idle_timeout", "cancelled", "owner_closed", "shutdown", "execution_error",
]
@dataclass(slots=True)
@@ -45,10 +49,27 @@ class _SessionPoll:
done: bool
exit_code: int | None
elapsed_s: float = 0.0
timed_out: bool = False
terminated: bool = False
finish_reason: FinishReason | None = None
stopping: bool = False
output_idle_s: float = 0.0
idle_timeout: int = 0
remaining_s: float | None = None
stdin_closed: bool = False
truncated_chars: int = 0
output_incomplete: bool = False
execution_error: str | None = None
@property
def failed(self) -> bool:
return self.timed_out or self.finish_reason == "execution_error"
@property
def timed_out(self) -> bool:
return self.finish_reason in ("max_runtime", "idle_timeout")
@property
def terminated(self) -> bool:
return self.finish_reason in ("cancelled", "owner_closed", "shutdown")
@dataclass(slots=True)
@@ -58,9 +79,13 @@ class ExecSessionInfo:
cwd: str
elapsed_s: float
idle_s: float
remaining_s: float
remaining_s: float | None
returncode: int | None
owner_session_key: str | None = None
idle_timeout: int = 0
stopping: bool = False
finish_reason: FinishReason | None = None
cleanup_error: str | None = None
class _BoundedOutputBuffer:
@@ -134,6 +159,9 @@ class _ExecSession:
timeout: int | None,
owner_session_key: str | None = None,
process_tree: bool = False,
idle_timeout: int = 300,
idle_action: Literal["report", "terminate"] = "report",
started_at: float | None = None,
) -> None:
self.session_id = session_id
self.process = process
@@ -141,32 +169,114 @@ class _ExecSession:
self.cwd = cwd
self.owner_session_key = owner_session_key
self._process_tree = process_tree
self.started_at = time.monotonic()
# timeout None/0 means no limit; an infinite deadline is never reached.
self.deadline = time.monotonic() + timeout if timeout else float("inf")
self.last_access = time.monotonic()
self.started_at = time.monotonic() if started_at is None else started_at
self.deadline = self.started_at + timeout if timeout else float("inf")
self.last_output_at: float | None = None
self.finished_at: float | None = None
self._execution_exited = False
self.idle_timeout = idle_timeout
self.idle_action = idle_action
self.finish_reason: FinishReason | None = None
self._stop_reason: FinishReason | None = None
self.cleanup_error: str | None = None
self._stop_complete = asyncio.Event()
self._state_changed = asyncio.Event()
self._output_incomplete = False
self._execution_error: str | None = None
self._stdout = _BoundedOutputBuffer(MAX_OUTPUT_CHARS)
self._stderr = _BoundedOutputBuffer(MAX_OUTPUT_CHARS)
self._lock = asyncio.Lock()
self._timed_out = False
self._kill_task: asyncio.Task[None] | None = None
self._stdout_task = asyncio.create_task(self._read_stream(process.stdout, self._stdout))
self._stderr_task = asyncio.create_task(self._read_stream(process.stderr, self._stderr))
self._timeout_task = asyncio.create_task(self._watch_timeout()) if timeout else None
self._completion_task = asyncio.create_task(self._complete())
self._completion_task.add_done_callback(self._on_supervisor_done)
self._timeout_task = (
asyncio.create_task(self._watch_timeout())
if timeout or (idle_timeout and idle_action == "terminate") else None
)
if self._timeout_task is not None:
self._timeout_task.add_done_callback(self._on_supervisor_done)
@property
def stopping(self) -> bool:
return self._stop_reason is not None and self.finished_at is None
def output_idle_s(self, now: float) -> float:
anchor = self.started_at if self.last_output_at is None else self.last_output_at
return max(0.0, now - anchor)
def remaining_s(self, now: float) -> float | None:
return max(0.0, self.deadline - now) if self.deadline != float("inf") else None
def _on_supervisor_done(self, task: asyncio.Task[None]) -> None:
if not task.cancelled() and (error := task.exception()) is not None:
if task is self._completion_task:
self.cleanup_error = str(error)
self._state_changed.set()
logger.opt(exception=error if tool_log_content_allowed() else False).error(
"Exec session supervision failed for {}", self.session_id,
)
async def _complete(self) -> None:
await self.process.wait()
# Root exit is not completion while a worker still holds captured pipes.
readers = asyncio.gather(self._stdout_task, self._stderr_task)
stopped = asyncio.create_task(self._stop_complete.wait())
try:
await asyncio.wait({readers, stopped}, return_when=asyncio.FIRST_COMPLETED)
if stopped.done():
try:
await asyncio.wait_for(readers, timeout=2.0)
except asyncio.TimeoutError:
self._output_incomplete = True
else:
await readers
self._execution_exited = True
if self._stop_reason is not None:
await stopped
finally:
stopped.cancel()
await asyncio.gather(stopped, return_exceptions=True)
from nanobot.agent.tools.shell import ExecTool, _reap_pid # pyright: ignore[reportPrivateUsage]
ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
_reap_pid(self.process.pid)
self.finish_reason = self._stop_reason or "exit"
self.finished_at = time.monotonic()
self._state_changed.set()
async def wait_exit(self) -> None:
while self.finished_at is None:
if self.cleanup_error is not None:
raise RuntimeError(f"session {self.session_id} cleanup failed: {self.cleanup_error}")
self._state_changed.clear()
await self._state_changed.wait()
async def _watch_timeout(self) -> None:
"""Enforce the hard deadline even when nobody polls this session."""
try:
await asyncio.wait_for(
self.process.wait(), timeout=max(0.0, self.deadline - time.monotonic()),
"""Supervise execution budgets independently of tool waits and log reads."""
while not self._completion_task.done():
now = time.monotonic()
deadline = self.deadline
if self.idle_timeout and self.idle_action == "terminate":
anchor = self.started_at if self.last_output_at is None else self.last_output_at
deadline = min(deadline, anchor + self.idle_timeout)
done, _ = await asyncio.wait(
{self._completion_task}, timeout=max(0.0, deadline - now),
)
except asyncio.TimeoutError:
if self.process.returncode is None:
if self._kill_task is None:
self._timed_out = True
# The kill callback logs failures; leave the session available for retry.
with suppress(Exception):
await self.kill()
if done:
return
if self._execution_exited:
await asyncio.shield(self._completion_task)
return
now = time.monotonic()
if now >= self.deadline:
await self.kill("max_runtime")
return
if self.idle_timeout and self.idle_action == "terminate":
if self.output_idle_s(now) >= self.idle_timeout:
await self.kill("idle_timeout")
return
async def _read_stream(
self,
@@ -177,13 +287,20 @@ class _ExecSession:
return
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
output_filter = ShellOutputFilter()
while True:
chunk = await stream.read(4096)
text = output_filter.feed(decoder.decode(chunk, final=not chunk))
async with self._lock:
buffer.append(text)
if not chunk:
break
try:
while True:
chunk = await stream.read(4096)
if chunk:
self.last_output_at = time.monotonic()
text = output_filter.feed(decoder.decode(chunk, final=not chunk))
async with self._lock:
buffer.append(text)
if not chunk:
break
except Exception as exc:
self._output_incomplete = True
self._execution_error = str(exc)
await self._begin_stop("execution_error")
async def write(self, chars: str) -> str | None:
if self.process.returncode is not None:
@@ -212,45 +329,16 @@ class _ExecSession:
yield_time_ms: int,
max_output_chars: int,
*,
terminated: bool = False,
stdin_closed: bool = False,
) -> _SessionPoll:
self.last_access = time.monotonic()
if yield_time_ms > 0 and self.process.returncode is None:
wait_s = min(yield_time_ms, MAX_YIELD_MS) / 1000
remaining_s = self.deadline - time.monotonic()
if remaining_s <= 0:
wait_s = 0
else:
wait_s = min(wait_s, remaining_s)
if wait_s > 0:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.process.wait(), timeout=wait_s)
if self.process.returncode is None and time.monotonic() >= self.deadline:
if self._kill_task is None:
self._timed_out = True
await self.kill()
if self._kill_task is not None:
# Finish termination before releasing process-tree ownership or returning output.
await asyncio.shield(self._kill_task)
if self.process.returncode is not None:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(
asyncio.gather(self._stdout_task, self._stderr_task),
timeout=2.0,
)
# Safety-net reap after normal exit.
from nanobot.agent.tools.shell import ( # pyright: ignore[reportPrivateUsage]
ExecTool,
_reap_pid, # pyright: ignore[reportPrivateUsage]
if yield_time_ms > 0 and not self._completion_task.done():
await asyncio.wait(
{self._completion_task}, timeout=min(yield_time_ms, MAX_YIELD_MS) / 1000,
)
ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
_reap_pid(self.process.pid) # pyright: ignore[reportPrivateUsage]
elif yield_time_ms > 0:
await self._wait_for_buffered_output()
if self._completion_task.done():
await asyncio.shield(self._completion_task)
if self.cleanup_error is not None:
raise RuntimeError(f"session {self.session_id} cleanup failed: {self.cleanup_error}")
async with self._lock:
stdout, stdout_truncated = self._stdout.drain()
@@ -261,22 +349,36 @@ class _ExecSession:
output_parts.append(f"STDERR:\n{stderr}")
output = "\n".join(output_parts)
output, response_truncated = _truncate_output(output, max_output_chars)
now = time.monotonic()
return _SessionPoll(
output=output,
done=self.process.returncode is not None,
done=self.finished_at is not None,
exit_code=self.process.returncode,
elapsed_s=max(0.0, time.monotonic() - self.started_at),
timed_out=self._timed_out,
terminated=terminated,
elapsed_s=max(0.0, (self.finished_at or now) - self.started_at),
finish_reason=self.finish_reason,
stopping=self.stopping,
output_idle_s=self.output_idle_s(now),
idle_timeout=self.idle_timeout,
remaining_s=self.remaining_s(now),
stdin_closed=stdin_closed,
truncated_chars=stdout_truncated + stderr_truncated + response_truncated,
output_incomplete=self._output_incomplete,
execution_error=self._execution_error,
)
async def kill(self) -> None:
# A cancelled poll must not cancel the session's process-tree cleanup.
if self._kill_task is None or (
self._kill_task.done() and self.process.returncode is None
):
async def kill(self, reason: FinishReason = "cancelled") -> None:
await self._begin_stop(reason)
await asyncio.shield(self._completion_task)
async def _begin_stop(self, reason: FinishReason) -> None:
if self.finished_at is not None:
return
if self._execution_exited and self._stop_reason is None:
return
if self._stop_reason is None:
self._stop_reason = reason
if self._kill_task is None:
self.cleanup_error = None
self._kill_task = asyncio.create_task(self._kill())
self._kill_task.add_done_callback(self._on_kill_done)
await asyncio.shield(self._kill_task)
@@ -284,6 +386,8 @@ class _ExecSession:
def _on_kill_done(self, task: asyncio.Task[None]) -> None:
error = None if task.cancelled() else task.exception()
if error is not None:
self.cleanup_error = str(error)
self._state_changed.set()
logger.opt(exception=error if tool_log_content_allowed() else False).error(
"Failed to terminate exec session {}", self.session_id,
)
@@ -293,36 +397,19 @@ class _ExecSession:
async def _kill(self) -> None:
from nanobot.agent.tools.shell import ExecTool
try:
if self._process_tree:
await ExecTool._kill_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
else:
await ExecTool._kill_process(self.process) # pyright: ignore[reportPrivateUsage]
finally:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(
asyncio.gather(
self._stdout_task,
self._stderr_task,
return_exceptions=True,
),
timeout=2.0,
)
async def _wait_for_buffered_output(self) -> None:
deadline = time.monotonic() + OUTPUT_DRAIN_GRACE_S
while time.monotonic() < deadline:
async with self._lock:
if self._stdout.has_output or self._stderr.has_output:
return
await asyncio.sleep(0.01)
if self._process_tree:
await ExecTool._kill_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
else:
await ExecTool._kill_process(self.process) # pyright: ignore[reportPrivateUsage]
self._stop_complete.set()
class ExecSessionManager:
def __init__(self, *, max_sessions: int = 8, idle_timeout: int = 1800) -> None:
def __init__(self, *, max_sessions: int = 8, result_retention: int = 1800) -> None:
self.max_sessions = max_sessions
self.idle_timeout = idle_timeout
self.result_retention = result_retention
self._sessions: dict[str, _ExecSession] = {}
self._starting: dict[str, tuple[str | None, asyncio.Task[_ExecSession]]] = {}
self._lock = asyncio.Lock()
self._closed = False
@@ -338,32 +425,86 @@ class ExecSessionManager:
yield_time_ms: int,
max_output_chars: int,
owner_session_key: str | None = None,
idle_timeout: int = 300,
idle_action: Literal["report", "terminate"] = "report",
stdin: int = asyncio.subprocess.PIPE,
until_exit: bool = False,
) -> tuple[str, _SessionPoll]:
async with self._lock:
if self._closed:
raise RuntimeError("exec session manager is closed")
await self._cleanup_locked()
if len(self._sessions) >= self.max_sessions:
raise RuntimeError(f"maximum exec sessions reached ({self.max_sessions})")
process = await self._spawn(command, cwd, env, shell_program, login)
self._cleanup_finished_locked()
if len(self._sessions) + len(self._starting) >= self.max_sessions:
finished = [
(session.finished_at, session_id)
for session_id, session in self._sessions.items()
if session.finished_at is not None
]
if not finished:
raise RuntimeError(f"maximum exec sessions reached ({self.max_sessions})")
self._sessions.pop(min(finished)[1])
session_id = uuid.uuid4().hex[:12]
session = _ExecSession(
session_id=session_id,
process=process,
command=shlex.join(command) if isinstance(command, list) else command,
cwd=cwd,
timeout=timeout,
owner_session_key=owner_session_key,
process_tree=True,
)
self._sessions[session_id] = session
poll = await session.poll(yield_time_ms, max_output_chars)
launch = asyncio.create_task(self._launch(
session_id=session_id, command=command, cwd=cwd, env=env,
timeout=timeout, shell_program=shell_program, login=login,
owner_session_key=owner_session_key, idle_timeout=idle_timeout,
idle_action=idle_action, stdin=stdin,
))
self._starting[session_id] = (owner_session_key, launch)
try:
session = await launch
if until_exit:
await session.wait_exit()
poll = await session.poll(yield_time_ms, max_output_chars)
except asyncio.CancelledError:
if launch.done() and not launch.cancelled() and launch.exception() is None:
await launch.result().kill("cancelled")
async with self._lock:
self._sessions.pop(session_id, None)
raise
finally:
async with self._lock:
self._starting.pop(session_id, None)
if poll.done:
async with self._lock:
self._sessions.pop(session_id, None)
return session_id, poll
async def _launch(
self, *, session_id: str, command: str | list[str], cwd: str,
env: dict[str, str], timeout: int | None, shell_program: str | None,
login: bool, owner_session_key: str | None, idle_timeout: int,
idle_action: Literal["report", "terminate"], stdin: int,
) -> _ExecSession:
session: _ExecSession | None = None
try:
started_at = time.monotonic()
process = await self._spawn(command, cwd, env, shell_program, login, stdin=stdin)
session = _ExecSession(
session_id=session_id, process=process,
command=shlex.join(command) if isinstance(command, list) else command,
cwd=cwd, timeout=timeout, owner_session_key=owner_session_key,
process_tree=True, idle_timeout=idle_timeout, idle_action=idle_action,
started_at=started_at,
)
async with self._lock:
if self._closed or session_id not in self._starting:
raise RuntimeError("exec session owner closed during startup")
self._sessions[session_id] = session
return session
except BaseException:
if session is not None:
try:
await session.kill("owner_closed")
except BaseException:
async with self._lock:
self._sessions[session_id] = session
raise
raise
finally:
async with self._lock:
self._starting.pop(session_id, None)
async def write(
self,
*,
@@ -376,7 +517,7 @@ class ExecSessionManager:
owner_session_key: str | None = None,
) -> _SessionPoll:
async with self._lock:
await self._cleanup_locked()
self._cleanup_finished_locked()
session = self._sessions.get(session_id)
if session is None:
raise KeyError(session_id)
@@ -398,7 +539,6 @@ class ExecSessionManager:
poll = await session.poll(
yield_time_ms,
max_output_chars,
terminated=terminate,
stdin_closed=stdin_closed,
)
if poll.done:
@@ -408,7 +548,7 @@ class ExecSessionManager:
async def list(self, *, owner_session_key: str | None = None) -> list[ExecSessionInfo]:
async with self._lock:
await self._cleanup_locked()
self._cleanup_finished_locked()
now = time.monotonic()
return [
ExecSessionInfo(
@@ -416,10 +556,14 @@ class ExecSessionManager:
command=session.command,
cwd=session.cwd,
elapsed_s=max(0.0, now - session.started_at),
idle_s=max(0.0, now - session.last_access),
remaining_s=max(0.0, session.deadline - now),
idle_s=session.output_idle_s(now),
remaining_s=session.remaining_s(now),
returncode=session.process.returncode,
owner_session_key=session.owner_session_key,
idle_timeout=session.idle_timeout,
stopping=session.stopping,
finish_reason=session.finish_reason,
cleanup_error=session.cleanup_error,
)
for session_id, session in sorted(self._sessions.items())
if session.owner_session_key == owner_session_key
@@ -431,26 +575,9 @@ class ExecSessionManager:
self._closed = True
sessions: list[_ExecSession] = list(self._sessions.values())
self._sessions.clear()
results: list[None | BaseException] = list(await asyncio.gather(
*(session.kill() for session in sessions),
return_exceptions=True,
))
failures: list[tuple[_ExecSession, BaseException]] = [
(session, result)
for session, result in zip(sessions, results, strict=True)
if isinstance(result, BaseException)
]
if failures:
async with self._lock:
for session, _ in failures:
self._sessions[session.session_id] = session
if len(failures) == 1:
raise failures[0][1]
raise BaseExceptionGroup(
"failed to close exec sessions",
[result for _, result in failures],
)
return len(sessions)
launches = [task for _, task in self._starting.values()]
self._starting.clear()
return await self._stop_owned(sessions, launches, "shutdown")
async def terminate_by_owner(self, owner_session_key: str) -> int:
"""Terminate all sessions owned by owner_session_key. Returns count."""
@@ -459,38 +586,61 @@ class ExecSessionManager:
for sid, s in list(self._sessions.items()):
if s.owner_session_key == owner_session_key:
victims.append(self._sessions.pop(sid))
launches = [
task for owner, task in self._starting.values() if owner == owner_session_key
]
for sid, (owner, _) in list(self._starting.items()):
if owner == owner_session_key:
self._starting.pop(sid)
return await self._stop_owned(victims, launches, "owner_closed")
async def _stop_owned(
self, sessions: list[_ExecSession], launches: list[asyncio.Task[_ExecSession]],
reason: FinishReason,
) -> int:
results: list[None | BaseException] = list(await asyncio.gather(
*(s.kill() for s in victims),
*(session.kill(reason) for session in sessions),
self._cancel_launches(launches),
return_exceptions=True,
))
failures: list[tuple[_ExecSession, BaseException]] = [
startup_error = results.pop()
failures = [
(session, result)
for session, result in zip(victims, results, strict=True)
for session, result in zip(sessions, results, strict=True)
if isinstance(result, BaseException)
]
if failures:
async with self._lock:
for session, _ in failures:
self._sessions[session.session_id] = session
if len(failures) == 1:
raise failures[0][1]
raise BaseExceptionGroup(
"failed to terminate exec sessions by owner",
[result for _, result in failures],
)
return len(victims)
errors = [result for _, result in failures]
if isinstance(startup_error, BaseException):
errors.append(startup_error)
if len(errors) == 1:
raise errors[0]
if errors:
raise BaseExceptionGroup("failed to stop owned exec sessions", errors)
return len(sessions) + len(launches)
async def _cleanup_locked(self) -> None:
@staticmethod
async def _cancel_launches(launches: list[asyncio.Task[_ExecSession]]) -> None:
for task in launches:
task.cancel()
results = await asyncio.gather(*launches, return_exceptions=True)
errors = [result for result in results if isinstance(result, Exception)]
if errors:
raise ExceptionGroup("failed to cancel exec startup", errors)
def _cleanup_finished_locked(self) -> None:
now = time.monotonic()
stale = [
session_id
for session_id, session in self._sessions.items()
if now - session.last_access > self.idle_timeout
if session.finished_at is not None
and now - session.finished_at > self.result_retention
]
for session_id in stale:
session = self._sessions[session_id]
await session.kill()
self._sessions.pop(session_id, None)
self._sessions.pop(session_id)
async def _spawn(
self,
@@ -499,12 +649,14 @@ class ExecSessionManager:
env: dict[str, str],
shell_program: str | None,
login: bool,
*,
stdin: int = asyncio.subprocess.PIPE,
) -> asyncio.subprocess.Process:
from nanobot.agent.tools.shell import ExecTool
return await ExecTool._spawn( # pyright: ignore[reportPrivateUsage]
command, cwd, env, shell_program, login,
stdin=asyncio.subprocess.PIPE,
stdin=stdin,
process_tree=True,
)
@@ -531,16 +683,30 @@ def format_session_poll(session_id: str, poll: _SessionPoll) -> str:
parts = [poll.output] if poll.output else []
if poll.truncated_chars:
parts.append(f"({poll.truncated_chars:,} chars truncated from output)")
if poll.timed_out:
parts.append("Error: Command timed out; session was terminated.")
if poll.terminated and not poll.timed_out:
parts.append("Session terminated.")
if poll.finish_reason == "max_runtime":
parts.append("Error: Command timed out; session was terminated. Reason: max_runtime.")
elif poll.finish_reason == "idle_timeout":
parts.append("Error: Output silence limit reached; session was terminated. Reason: idle_timeout.")
elif poll.terminated:
parts.append(f"Session terminated. Reason: {poll.finish_reason}.")
elif poll.finish_reason == "execution_error":
parts.append(f"Error: Command output failed: {poll.execution_error}. Reason: execution_error.")
if poll.output_incomplete:
parts.append("Output collection ended before EOF; output may be incomplete.")
if poll.stdin_closed:
parts.append("Stdin closed.")
if poll.done:
parts.append(f"Exit code: {poll.exit_code}")
else:
parts.append(f"Process running. session_id: {session_id}")
state = "stopping" if poll.stopping else "running"
parts.append(f"Process {state}. session_id: {session_id}")
if poll.idle_timeout and poll.output_idle_s >= poll.idle_timeout:
parts.append(
f"Output silent for {poll.output_idle_s:.1f}s; "
"no stdout/stderr bytes observed. This does not establish a stall."
)
remaining = "unlimited" if poll.remaining_s is None else f"{poll.remaining_s:.1f}s"
parts.append(f"Runtime remaining: {remaining}")
parts.append(f"Elapsed: {poll.elapsed_s:.1f}s")
return "\n".join(parts) if parts else "(no output yet)"
@@ -654,7 +820,7 @@ class ExecSessionTool(Tool):
owner_session_key=current_request_session_key(),
)
result = format_session_poll(session_id, poll)
return ToolResult.error(result) if poll.timed_out else result
return ToolResult.error(result) if poll.failed else result
default_timeout_ms = (
DEFAULT_UNTIL_EXIT_MS
@@ -728,12 +894,12 @@ class ExecSessionTool(Tool):
result = format_session_poll(session_id, poll)
if wait_for is not None and not matched:
result += f"\nWait target not observed: {wait_for!r}"
elif until_exit and not poll.done:
if expired and not poll.done and not matched:
result += (
f"\nWait timed out after {timeout_ms / 1000:g}s; "
"session remains active."
)
return ToolResult.error(result) if poll.timed_out else result
return ToolResult.error(result) if poll.failed else result
@tool_parameters(tool_parameters_schema())
@@ -786,12 +952,19 @@ class ListExecSessionsTool(Tool):
command = " ".join(info.command.split())
if len(command) > 120:
command = command[:119] + "..."
status = "exited" if info.returncode is not None else "running"
status = "finished" if info.finish_reason is not None else (
"stopping" if info.stopping else "running"
)
remaining = "unlimited" if info.remaining_s is None else f"{info.remaining_s:.1f}s"
silent = bool(info.idle_timeout and info.idle_s >= info.idle_timeout)
lines.append(
f"{info.session_id} | {status} | elapsed={info.elapsed_s:.1f}s "
f"| idle={info.idle_s:.1f}s | remaining={info.remaining_s:.1f}s "
f"| output_idle={info.idle_s:.1f}s | silent={str(silent).lower()} "
f"| remaining={remaining} | reason={info.finish_reason or '-'} "
f"| cwd={info.cwd} | {command}"
)
if info.cleanup_error is not None:
lines.append(f"Cleanup failed: {info.cleanup_error}")
return "\n".join(lines)
except Exception as exc:
return ToolResult.error(f"Error listing exec sessions: {exc}")