Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 33 additions & 10 deletions python/packages/tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ output (`stdout`) and error output (`stderr`):
from agent_framework.tools import DockerShellTool, LocalShellTool

local_shell = LocalShellTool(max_stdout_bytes=16 * 1024, max_stderr_bytes=4 * 1024)
docker_shell = DockerShellTool(max_stdout_bytes=16 * 1024, max_stderr_bytes=4 * 1024)
docker_shell = DockerShellTool(
docker_binary="/usr/bin/docker", max_stdout_bytes=16 * 1024, max_stderr_bytes=4 * 1024
)
```

These settings limit retained output, not how much a command may produce.
Expand All @@ -126,13 +128,30 @@ are not stopped solely because either output allowance is exceeded.
- **Linux / macOS**: `/bin/bash --noprofile --norc` (falls back to `/bin/sh`).
- Override via the `shell=` constructor argument or the
`AGENT_FRAMEWORK_SHELL` environment variable.
- **Windows executable lookup**: a bare executable name (the default `pwsh` or
`powershell`, a bare `shell=` or `AGENT_FRAMEWORK_SHELL` value, and the
`docker_binary` of `DockerShellTool`) is looked up only in the fully
qualified entries of `PATH`. The current directory and relative `PATH`
entries are never searched. Pass an absolute path to select a specific
executable. A path, like a `PATH` match, shows only that the file exists, not
that it can be trusted, so keep `PATH` and the directories on it protected.
- **Full paths required**: `shell=`, `AGENT_FRAMEWORK_SHELL`, and the
`docker_binary` of `DockerShellTool` must be full paths, such as
`/usr/bin/zsh` or `C:\Program Files\PowerShell\7\pwsh.exe`. On Windows the
path must also include the file extension. Short names (`zsh`) and relative
paths (`bin/zsh`, `.\pwsh.exe`) are rejected, because they could pick up a
file in the current directory. On Windows, wrap a path that contains spaces
in double quotes when passing it as a string, for example
`"C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo`, or pass `shell=` as a
list.
- **Default shell lookup**: the Windows default (`pwsh.exe`, then
`powershell.exe`) is looked up only in the fully qualified entries of
`PATH`. The current directory and relative `PATH` entries are never
searched.
- **Shell `PATH`**: before the shell starts, empty and relative entries (such
as `.` or `bin`) are removed from its `PATH`, so commands it runs are never
looked up in the current directory. On Windows,
`NoDefaultCurrentDirectoryInExePath=1` is also set, so `cmd.exe` runs a
program from the working directory only when the command gives its relative
path (for example `.\tool`). On Linux and macOS, `LocalShellTool` raises
`ValueError` if no full directory path is left in `PATH` (for example
`clean_env=True` without a `PATH` in `env`), because an empty or missing
`PATH` would search the current directory. This can't be turned off.
- A path, like a `PATH` match, shows only that the file exists, not that it can
be trusted, so keep `PATH` and the directories on it protected.

## `ShellEnvironmentProvider` — context provider

Expand Down Expand Up @@ -182,6 +201,7 @@ from agent_framework.tools import DockerShellTool

async def main() -> None:
async with DockerShellTool(
docker_binary="/usr/bin/docker", # full path to the container runtime
image="mcr.microsoft.com/azurelinux/base/core:3.0",
approval_mode="never_require", # container is the boundary
) as shell:
Expand All @@ -201,8 +221,11 @@ Defaults applied to every container:
- `--memory 512m`, `--pids-limit 256`, ephemeral `tmpfs /tmp`.

To expose a host directory, pass `host_workdir="/path"` (mounted
read-only by default; `mount_readonly=False` to allow writes). Swap the
container runtime with `docker_binary="podman"`.
read-only by default; `mount_readonly=False` to allow writes).
`docker_binary` is required and must be the full path to the container
runtime (for example `docker_binary="/usr/bin/podman"` to use Podman). On
Windows include the extension, for example
`C:\Program Files\Docker\Docker\resources\bin\docker.exe`.

Applications that must pass additional Docker options can use
`unsafe_extra_run_args`. These trusted setup options are appended verbatim
Expand Down
59 changes: 25 additions & 34 deletions python/packages/tools/agent_framework_tools/shell/_docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
import logging
import os
import secrets
import shutil
import subprocess # ruff:ignore[suspicious-subprocess-import] # nosec B404 - running shell commands is the whole point of this tool
import time
from collections.abc import Callable, Mapping, Sequence
Expand All @@ -59,7 +58,7 @@
from .._feature_usage import FeatureIndex
from ._capture import _ProcessOutput # pyright: ignore[reportPrivateUsage] - shared shell capture
from ._policy import ShellPolicy, ShellRequest
from ._resolve import resolve_executable
from ._resolve import require_full_path
from ._session import ShellSession
from ._truncate import _validate_output_limit # pyright: ignore[reportPrivateUsage] - shared limit validation
from ._types import (
Expand Down Expand Up @@ -92,17 +91,19 @@ class DockerNotAvailableError(RuntimeError):
"""Raised when the configured docker binary cannot be reached."""


def is_docker_available(binary: str = "docker") -> bool:
"""Return ``True`` if ``binary`` is on PATH and the daemon responds.
def is_docker_available(binary: str) -> bool:
"""Return ``True`` if the container runtime at ``binary`` exists and its daemon responds.

On Windows, a bare ``binary`` is looked up only in the fully qualified entries of ``PATH``. The
current directory is never searched.
Args:
binary: Full path to the ``docker`` (or compatible, such as ``podman``) executable. On
Windows it must include the file extension. A short name or relative path returns
``False`` because it could be resolved from the current directory.
"""
try:
binary = resolve_executable(binary)
except FileNotFoundError:
require_full_path(binary, source="binary")
except ValueError:
return False
if shutil.which(binary) is None:
if not os.path.isfile(binary):
return False
try:
out = subprocess.run( # ruff:ignore[subprocess-without-shell-equals-true] # nosec B603 - argv is built from trusted binary name
Expand Down Expand Up @@ -240,6 +241,12 @@ class DockerShellTool:
docstring for more.

Args:
docker_binary: Required full path to the ``docker`` (or compatible,
such as ``podman``) executable, for example ``"/usr/bin/docker"``.
On Windows it must also include the file extension (``.exe``).
Short names and relative paths are rejected because they could be
resolved from the current directory. A path shows only that the
file is there, not that it can be trusted.
image: OCI image to run. Defaults to a small Microsoft-maintained
base image. Override with anything that includes ``bash`` and
(for persistent mode) ``sleep``.
Expand Down Expand Up @@ -287,11 +294,6 @@ class DockerShellTool:
with the default isolation flags and a trusted runtime — is
the intended boundary rather than approval.
on_command: Audit hook fired for every allowed command.
docker_binary: Override (e.g. ``"podman"``). On Windows, a bare name is
looked up only in the fully qualified entries of ``PATH``; the current
directory is never searched. Pass an absolute path to select a specific
executable. A path, like a ``PATH`` match, shows only that the file
exists, not that it can be trusted.
shell: Shell binary to invoke inside the container. Defaults to
``"bash"``; pass ``"sh"`` for minimal images such as Alpine
that don't ship bash. Anything else must be present on
Expand All @@ -301,6 +303,7 @@ class DockerShellTool:
def __init__(
self,
*,
docker_binary: str,
image: str = DEFAULT_IMAGE,
container_name: str | None = None,
mode: ShellMode = "persistent",
Expand All @@ -320,7 +323,6 @@ def __init__(
max_stderr_bytes: int = 64 * 1024,
approval_mode: Literal["always_require", "never_require"] = "always_require",
on_command: Callable[[str], None] | None = None,
docker_binary: str = "docker",
shell: str = "bash",
) -> None:
_validate_output_limit(max_stdout_bytes, name="max_stdout_bytes")
Expand Down Expand Up @@ -348,10 +350,9 @@ def __init__(
self._max_stderr_bytes = max_stderr_bytes
self._approval_mode: Literal["always_require", "never_require"] = approval_mode
self._on_command = on_command
self._binary = docker_binary
self._binary = require_full_path(docker_binary, source="docker_binary")
self._shell = shell

self._resolved_binary: str | None = None
self._session: ShellSession | None = None
self._container_started = False
self._lifecycle_lock: asyncio.Lock | None = None
Expand All @@ -361,23 +362,13 @@ def _get_lifecycle_lock(self) -> asyncio.Lock:
self._lifecycle_lock = asyncio.Lock()
return self._lifecycle_lock

def _runtime_path(self) -> str:
"""Return the container runtime to launch, resolved once for this instance.

Resolving once keeps every launch of one instance on the same executable, so the runtime that
started a container is also the one that stops it.
"""
if self._resolved_binary is None:
self._resolved_binary = resolve_executable(self._binary)
return self._resolved_binary

# ------------------------------------------------------------------ lifecycle

async def start(self) -> None:
"""Pull/start the container and (if persistent) the inner shell session.

Raises:
FileNotFoundError: If the container runtime executable cannot be found.
FileNotFoundError: If the container runtime executable does not exist.
"""
# Stateless mode never uses the long-lived container — every call goes
# through ``docker run --rm`` — so start()/close() are no-ops.
Expand All @@ -391,7 +382,7 @@ async def start(self) -> None:
await self._start_container()
self._container_started = True
argv = build_exec_argv(
binary=self._runtime_path(),
binary=self._binary,
container_name=self._container_name,
interactive=True,
shell=self._shell, # nosec B604 - 'shell' is the binary name kwarg, not subprocess shell=True
Expand Down Expand Up @@ -467,7 +458,7 @@ async def _run_stateless(self, command: str, *, timeout: float | None) -> ShellR
"""Run a single command in a fresh ``docker run --rm`` container."""
per_call_name = f"af-shell-{secrets.token_hex(6)}"
argv = [
self._runtime_path(),
self._binary,
"run",
"--rm",
"-i",
Expand Down Expand Up @@ -538,7 +529,7 @@ async def _terminate_stateless(self, proc: asyncio.subprocess.Process, name: str
# Stopping the local client alone does not stop its container.
try:
killer = await asyncio.create_subprocess_exec(
self._runtime_path(),
self._binary,
"kill",
"--signal",
"KILL",
Expand All @@ -562,7 +553,7 @@ async def _terminate_stateless(self, proc: asyncio.subprocess.Process, name: str
if not kill_ok:
logger.warning("docker kill of %s did not succeed; attempting docker rm -f", name)
reaper = await asyncio.create_subprocess_exec(
self._runtime_path(),
self._binary,
"rm",
"-f",
name,
Expand Down Expand Up @@ -598,7 +589,7 @@ async def _terminate_stateless(self, proc: asyncio.subprocess.Process, name: str

async def _start_container(self) -> None:
argv = build_run_argv(
binary=self._runtime_path(),
binary=self._binary,
image=self._image,
container_name=self._container_name,
user=self._user,
Expand Down Expand Up @@ -634,7 +625,7 @@ async def _stop_container(self) -> None:
async def _attempt(timeout: float) -> tuple[int | None, str]:
"""Run a single ``docker rm -f`` attempt. Returns (rc, stderr)."""
proc = await asyncio.create_subprocess_exec(
self._runtime_path(),
self._binary,
"rm",
"-f",
self._container_name,
Expand Down
Loading
Loading