Code Execution Backends
The stirrup.tools.code_backends module provides code execution backends.
CodeExecToolProvider (Base Class)
stirrup.tools.code_backends.CodeExecToolProvider
CodeExecToolProvider(
*,
allowed_commands: list[str] | None = None,
shell_timeout: int = SHELL_TIMEOUT,
)
Bases: ToolProvider, ABC
Abstract base class for code execution tool providers.
CodeExecToolProvider is a ToolProvider that manages code execution environments (sandboxes, containers, local temp directories) and returns a code_exec Tool.
Subclasses must implement: - aenter(): Initialize environment and return the code_exec tool - aexit(): Cleanup the execution environment - run_command(): Execute a command and return raw result - read_file_bytes(): Read file content as bytes from the environment - write_file_bytes(): Write bytes to a file in the environment
Default implementations are provided for: - save_output_files(): Save files to local dir or another exec env (uses primitives) - upload_files(): Upload files from local or another exec env (uses primitives)
Overridable output-path hooks (see the extending docs for the contract): - output_source_roots(): Declare absolute roots for resolving output paths - resolve_output_source(): Resolve/reject a source before it is read - output_destination_identity(): Reject escapes and identify cross-env destinations
All providers accept an optional allowlist of command patterns. With an allowlist, each command is parsed with shlex, matched against the patterns, and executed without a shell: arguments are passed literally, and shell syntax such as pipes, redirects, and expansions is rejected. Without an allowlist, all commands are allowed and run through a shell.
Usage with Agent
from stirrup.clients.chat_completions_client import ChatCompletionsClient
client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="assistant", tools=[LocalCodeExecToolProvider(), CALCULATOR_TOOL], )
Initialize execution environment with optional command allowlist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allowed_commands
|
list[str] | None
|
Optional list of regex patterns, matched from the
start of the parsed command. When set, commands run
without a shell: arguments are literal and shell
syntax is rejected (see |
None
|
shell_timeout
|
int
|
Per-command wall-clock timeout (seconds) applied to
every |
SHELL_TIMEOUT
|
Source code in src/stirrup/tools/code_backends/base.py
run_command
abstractmethod
async
run_command(
cmd: str, *, timeout: int | None = None
) -> CommandResult
Execute a shell command and return raw CommandResult.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str
|
Shell command to execute (bash syntax). |
required |
timeout
|
int | None
|
Per-call wall-clock timeout (seconds). If None, falls back
to |
None
|
Source code in src/stirrup/tools/code_backends/base.py
read_file_bytes
abstractmethod
async
Read file content as bytes from this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path within this execution environment (relative or absolute within the env's working directory). |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
File contents as bytes. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file does not exist. |
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
write_file_bytes
abstractmethod
async
Write bytes to a file in this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Destination path within this execution environment. |
required |
content
|
bytes
|
File contents to write. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
save_output_files
async
save_output_files(
paths: list[str],
output_dir: Path | str,
dest_env: CodeExecToolProvider | None = None,
) -> SaveOutputFilesResult
Save files from this execution environment to a destination.
Each source path is preserved relative to output_dir: relative
sources keep their directory structure, and absolute sources are made
relative to a matching root from output_source_roots(). Sources
that are empty, contain traversal, fall outside every declared root,
or fail resolve_output_source() are rejected, and a second source
that resolves to an already-claimed destination is rejected rather
than overwriting it (first requested output wins). Every rejection is
recorded in SaveOutputFilesResult.failed as source_path ->
reason. All implementations copy files and leave sources in place.
Host-backed providers preserve file modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of file paths in this execution environment to save. |
required |
output_dir
|
Path | str
|
Directory path to save files to. |
required |
dest_env
|
CodeExecToolProvider | None
|
If provided, output_dir is interpreted as a path within dest_env (cross-environment transfer). If None, output_dir is a local filesystem path. |
None
|
Returns:
| Type | Description |
|---|---|
SaveOutputFilesResult
|
SaveOutputFilesResult containing lists of saved files and any failures. |
Source code in src/stirrup/tools/code_backends/base.py
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 | |
upload_files
async
upload_files(
*paths: Path | str,
source_env: CodeExecToolProvider | None = None,
dest_dir: str | None = None,
) -> UploadFilesResult
Upload files to this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
Path | str
|
File or directory paths to upload. If source_env is None, these are local filesystem paths. If source_env is provided, these are paths within source_env (cross-environment transfer). |
()
|
source_env
|
CodeExecToolProvider | None
|
If provided, paths are within source_env. If None, paths are local filesystem paths. |
None
|
dest_dir
|
str | None
|
Destination directory in this environment. If None, uses the environment's working directory. |
None
|
Returns:
| Type | Description |
|---|---|
UploadFilesResult
|
UploadFilesResult containing lists of uploaded files and any failures. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 | |
get_code_exec_tool
get_code_exec_tool(
*,
name: str = "code_exec",
description: str | None = None,
) -> Tool[CodeExecutionParams, ToolUseCountMetadata]
Create a code execution tool for this environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Tool name |
'code_exec'
|
description
|
str | None
|
Tool description |
None
|
Returns:
| Type | Description |
|---|---|
Tool[CodeExecutionParams, ToolUseCountMetadata]
|
Tool[CodeExecutionParams] that executes commands in this environment |
Source code in src/stirrup/tools/code_backends/base.py
get_view_image_tool
get_view_image_tool(
*,
name: str = "view_image",
description: str | None = None,
) -> Tool[ViewImageParams, ToolUseCountMetadata]
Create a view_image tool for this environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Tool name |
'view_image'
|
description
|
str | None
|
Tool description |
None
|
Returns:
| Type | Description |
|---|---|
Tool[ViewImageParams, ToolUseCountMetadata]
|
Tool[ViewImageParams, ToolUseCountMetadata] that views images in this environment |
Source code in src/stirrup/tools/code_backends/base.py
LocalCodeExecToolProvider
Executes code in an isolated temporary directory on the host machine.
stirrup.tools.code_backends.LocalCodeExecToolProvider
LocalCodeExecToolProvider(
*,
allowed_commands: list[str] | None = None,
temp_base_dir: Path | str | None = None,
description: str | None = None,
shell_timeout: int = SHELL_TIMEOUT,
)
Bases: CodeExecToolProvider
Local code execution tool provider using an isolated temp directory.
Commands are executed with the temp directory as the working directory. An optional allowlist can restrict which commands are permitted.
Usage with Agent
from stirrup.clients.chat_completions_client import ChatCompletionsClient
client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="assistant", tools=[LocalCodeExecToolProvider(), CALCULATOR_TOOL], )
async with agent.session(output_dir="./output") as session: await session.run("Run some Python code")
Standalone usage
provider = LocalCodeExecToolProvider()
async with provider as tool: # tool is a Tool instance for code execution result = await provider.run_command("python script.py") await provider.save_output_files(["output.txt"], "/path/to/output")
Initialize LocalCodeExecToolProvider configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allowed_commands
|
list[str] | None
|
Optional list of regex patterns. When set, commands are matched against the patterns and run without a shell, with literal arguments. When None, all commands are allowed and run through bash. |
None
|
temp_base_dir
|
Path | str | None
|
Optional base directory for creating the execution environment temp directory. If None, uses the system default temp directory. |
None
|
description
|
str | None
|
Optional description of the tool. If None, uses the default description. |
None
|
shell_timeout
|
int
|
Per-command wall-clock timeout (seconds) for every
|
SHELL_TIMEOUT
|
Source code in src/stirrup/tools/code_backends/local.py
_temp_base_dir
instance-attribute
_description
instance-attribute
_description = (
description
or "Execute a shell command in the execution environment. Returns exit code, stdout, and stderr as XML. Use `uv` to manage packages."
)
_check_absolute_paths
_check_absolute_paths(cmd: str) -> CommandResult | None
Check if command contains absolute paths that could escape the temp directory.
Returns:
| Type | Description |
|---|---|
CommandResult | None
|
CommandResult with error if absolute paths detected, None otherwise. |
Note
This check is specific to LocalCodeExecToolProvider since Docker and E2B providers are already sandboxed and absolute paths are safe within them.
Source code in src/stirrup/tools/code_backends/local.py
__aenter__
async
__aenter__() -> Tool[
CodeExecutionParams, ToolUseCountMetadata
]
Create temp directory and return the code_exec tool.
Source code in src/stirrup/tools/code_backends/local.py
__aexit__
async
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> None
Cleanup the local execution environment.
Source code in src/stirrup/tools/code_backends/local.py
_resolve_and_validate_path
Resolve a path and validate it's within the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Resolved absolute Path. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
FileNotFoundError
|
If path does not exist (for reads). |
Source code in src/stirrup/tools/code_backends/local.py
read_file_bytes
async
Read file content as bytes from the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
File contents as bytes. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
FileNotFoundError
|
If file does not exist. |
Source code in src/stirrup/tools/code_backends/local.py
write_file_bytes
async
Write bytes to a file in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Destination path (relative or absolute within the temp dir). |
required |
content
|
bytes
|
File contents to write. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
Source code in src/stirrup/tools/code_backends/local.py
file_exists
async
Check if a file exists in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the file exists, False otherwise. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
Source code in src/stirrup/tools/code_backends/local.py
is_directory
async
Check if a path is a directory in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the path exists and is a directory, False otherwise. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
Source code in src/stirrup/tools/code_backends/local.py
list_files
async
List all files recursively in a directory within the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Directory path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of file paths (relative to the given path) for all files in the directory. |
list[str]
|
Returns an empty list if the path is a file or doesn't exist. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
Source code in src/stirrup/tools/code_backends/local.py
run_command
async
run_command(
cmd: str, *, timeout: int | None = None
) -> CommandResult
Execute command in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str
|
Shell command to execute (bash syntax). |
required |
timeout
|
int | None
|
Maximum time in seconds to wait for command completion.
If None, falls back to |
None
|
Returns:
| Type | Description |
|---|---|
CommandResult
|
CommandResult with exit_code, stdout, stderr, and optional error info. |
Source code in src/stirrup/tools/code_backends/local.py
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
save_output_files
async
save_output_files(
paths: list[str],
output_dir: Path | str,
dest_env: CodeExecToolProvider | None = None,
) -> SaveOutputFilesResult
Copy files from the temp directory to a destination.
Source files remain in the execution environment. Existing destination
files are atomically replaced, while duplicate destinations within one
call are rejected and reported in failed.
When dest_env is provided (cross-environment transfer), files are copied using the base class implementation via read/write primitives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of file paths in the execution environment (relative or absolute). Relative paths are resolved against the execution environment temp directory. |
required |
output_dir
|
Path | str
|
Directory path to save files to. |
required |
dest_env
|
CodeExecToolProvider | None
|
If provided, output_dir is interpreted as a path within dest_env (cross-environment transfer). If None, output_dir is a local filesystem path. |
None
|
Returns:
| Type | Description |
|---|---|
SaveOutputFilesResult
|
SaveOutputFilesResult containing lists of saved files and any failures. |
Source code in src/stirrup/tools/code_backends/local.py
output_source_roots
output_source_roots() -> tuple[OutputSourceRoot, ...]
Return absolute execution roots accepted when resolving output paths.
output_destination_identity
async
Validate a cross-environment destination and return its host identity.
Source code in src/stirrup/tools/code_backends/local.py
upload_files
async
upload_files(
*paths: Path | str,
source_env: CodeExecToolProvider | None = None,
dest_dir: str | None = None,
) -> UploadFilesResult
Upload files to the execution environment.
When source_env is None (local filesystem), files are COPIED (not moved) - originals remain on the local filesystem. Directories are uploaded recursively, preserving their structure.
When source_env is provided (cross-environment transfer), files are copied using the base class implementation via read/write primitives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
Path | str
|
File or directory paths to upload. If source_env is None, these are local filesystem paths. If source_env is provided, these are paths within source_env. |
()
|
source_env
|
CodeExecToolProvider | None
|
If provided, paths are within source_env. If None, paths are local filesystem paths. |
None
|
dest_dir
|
str | None
|
Destination subdirectory within the temp directory. If None, files are placed directly in the temp directory. |
None
|
Returns:
| Type | Description |
|---|---|
UploadFilesResult
|
UploadFilesResult containing lists of uploaded files and any failures. |
Source code in src/stirrup/tools/code_backends/local.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 | |
view_image
async
view_image(path: str) -> ImageContentBlock
Read and return an image file from the local execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to image file (relative to temp directory, or absolute within it). |
required |
Returns:
| Type | Description |
|---|---|
ImageContentBlock
|
ImageContentBlock containing the image data. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
FileNotFoundError
|
If file does not exist. |
ValueError
|
If path is outside temp directory, is a directory, or not a valid image. |
Source code in src/stirrup/tools/code_backends/local.py
DockerCodeExecToolProvider
Executes code in a Docker container.
Note
Requires pip install stirrup[docker] (or: uv add stirrup[docker])
from stirrup.tools.code_backends.docker import DockerCodeExecToolProvider
provider = DockerCodeExecToolProvider.from_image("python:3.12-slim")
E2BCodeExecToolProvider
Executes code in an E2B cloud sandbox.
Note
Requires pip install stirrup[e2b] (or: uv add stirrup[e2b]) and E2B_API_KEY environment variable.
from stirrup.tools.code_backends.e2b import E2BCodeExecToolProvider
provider = E2BCodeExecToolProvider()
Data Types
stirrup.tools.code_backends.CodeExecutionParams
Bases: BaseModel
Shell command to execute in the execution environment.
stirrup.tools.code_backends.CommandResult
dataclass
CommandResult(
exit_code: int,
stdout: str,
stderr: str,
error_kind: str | None = None,
advice: str | None = None,
)
Raw result from command execution (before formatting).