Skip to content

Commit 4d4ce4a

Browse files
seratchFilimoa
andcommitted
feat: add run-scoped sandbox working directories
Co-authored-by: Sergey Filimonov <[email protected]>
1 parent 1a0c088 commit 4d4ce4a

30 files changed

Lines changed: 2523 additions & 69 deletions

‎examples/sandbox/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Most examples call a model through `Runner`, so set `OPENAI_API_KEY` in the repo
1919
| [`memory.py`](./memory.py) | `uv run python examples/sandbox/memory.py` | Runs one sandbox agent twice across a snapshot resume so it can read and write its own memory. |
2020
| [`memory_s3.py`](./memory_s3.py) | `source ~/.s3.env && uv run python examples/sandbox/memory_s3.py` | Runs sandbox memory across two fresh Docker sandboxes with S3-backed memory storage. |
2121
| [`memory_multi_agent_multiturn.py`](./memory_multi_agent_multiturn.py) | `uv run python examples/sandbox/memory_multi_agent_multiturn.py` | Shows separate memory layouts for two agents sharing one sandbox workspace. |
22+
| [`shared_session_workdirs.py`](./shared_session_workdirs.py) | `uv run python examples/sandbox/shared_session_workdirs.py` | Shares one live sandbox between trusted agents while Shell, `view_image`, and `apply_patch` resolve relative paths from each run's `cwd`. This is not confinement; use separate sessions for untrusted agents or compute isolation. |
2223
| [`unix_local_pty.py`](./unix_local_pty.py) | `uv run python examples/sandbox/unix_local_pty.py` | Exercises an interactive pseudo-terminal in a Unix-local sandbox. |
2324
| [`unix_local_runner.py`](./unix_local_runner.py) | `uv run python examples/sandbox/unix_local_runner.py` | Runs against the Unix-local sandbox backend directly. |
2425

Lines changed: 289 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,289 @@
1+
"""Run two trusted agents in separate working directories of one live sandbox.
2+
3+
Run-scoped working directories make relative paths consistent; they are not confinement.
4+
Use separate sandbox sessions for untrusted agents or workloads that need compute isolation.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
import argparse
10+
import asyncio
11+
import base64
12+
import json
13+
from pathlib import Path
14+
15+
from agents import ModelSettings, Runner, RunResult, ToolOutputImage
16+
from agents.items import ToolCallItem, ToolCallOutputItem
17+
from agents.run import RunConfig
18+
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
19+
from agents.sandbox.capabilities import Filesystem, Shell
20+
from agents.sandbox.entries import BaseEntry, Dir, File
21+
from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient
22+
from agents.sandbox.session import BaseSandboxSession
23+
24+
25+
async def main(*, model: str) -> None:
26+
client = UnixLocalSandboxClient()
27+
agent_a = _build_agent(name="Task A worker", model=model)
28+
agent_b = _build_agent(name="Task B worker", model=model)
29+
shared_sandbox = await client.create(manifest=_build_manifest())
30+
31+
try:
32+
# The session is shared, but each run gets a different base for relative paths.
33+
run_a_config = RunConfig(
34+
sandbox=SandboxRunConfig(
35+
session=shared_sandbox,
36+
cwd="tasks/task-a",
37+
),
38+
workflow_name="Shared sandbox task A",
39+
)
40+
run_b_config = RunConfig(
41+
sandbox=SandboxRunConfig(
42+
session=shared_sandbox,
43+
cwd="tasks/task-b",
44+
),
45+
workflow_name="Shared sandbox task B",
46+
)
47+
48+
async with shared_sandbox:
49+
run_tasks = [
50+
asyncio.create_task(
51+
Runner.run(
52+
agent_a,
53+
_task_prompt("task-a"),
54+
run_config=run_a_config,
55+
max_turns=10,
56+
)
57+
),
58+
asyncio.create_task(
59+
Runner.run(
60+
agent_b,
61+
_task_prompt("task-b"),
62+
run_config=run_b_config,
63+
max_turns=10,
64+
)
65+
),
66+
]
67+
result_a, result_b = await _run_concurrently(run_tasks)
68+
69+
# These checks make the demo self-verifying; applications do not need them.
70+
await _verify_task(shared_sandbox, task_name="task-a", result=result_a)
71+
await _verify_task(shared_sandbox, task_name="task-b", result=result_b)
72+
finally:
73+
await client.delete(shared_sandbox)
74+
75+
print("\nVerified: distinct run-scoped cwd values worked without session-global cwd mutation.")
76+
77+
78+
# Demo setup. Applications can create task directories and inputs however they prefer.
79+
80+
DEFAULT_MODEL = "gpt-5.6-sol"
81+
82+
# The two task directories intentionally contain the same relative filenames.
83+
TASKS = {
84+
"task-a": (
85+
"red",
86+
"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKklEQVR4nGO4o6ZGU8QwasGoBaMWjFowasGoBaMWjFowasGoBaMWDBULAIjyoD0k0I5JAAAAAElFTkSuQmCC",
87+
),
88+
"task-b": (
89+
"blue",
90+
"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKklEQVR4nGNQTX5NU8QwasGoBaMWjFowasGoBaMWjFowasGoBaMWDBULAMMtzEwilX6gAAAAAElFTkSuQmCC",
91+
),
92+
}
93+
94+
SHELL_COMMAND = "cp reference.png page.png && cat brief.md"
95+
96+
97+
def _task_prompt(task_name: str) -> str:
98+
return f"""
99+
Complete {task_name} in your current run working directory. Use only these relative paths:
100+
101+
1. Call `exec_command` with `{SHELL_COMMAND}`. Do not pass `workdir`.
102+
2. Call `view_image` with `page.png` and identify its color.
103+
3. Use `apply_patch` on `notes.md` to change only `status=pending-{task_name}` to
104+
`status=complete-{task_name}`.
105+
4. Reply with the task name and image color from the files you inspected.
106+
107+
Do not prefix paths with `tasks/`, use absolute paths, or use the shell to edit `notes.md`.
108+
""".strip()
109+
110+
111+
def _build_manifest() -> Manifest:
112+
task_dirs: dict[str | Path, BaseEntry] = {}
113+
for task_name, (color, image_base64) in TASKS.items():
114+
task_dirs[task_name] = Dir(
115+
children={
116+
"brief.md": File(
117+
content=f"# {task_name}\n\nThe reference image is {color}.\n".encode()
118+
),
119+
"reference.png": File(content=base64.b64decode(image_base64)),
120+
"notes.md": File(
121+
content=f"task={task_name}\nstatus=pending-{task_name}\n".encode()
122+
),
123+
}
124+
)
125+
return Manifest(entries={"tasks": Dir(children=task_dirs)})
126+
127+
128+
def _build_agent(*, name: str, model: str) -> SandboxAgent:
129+
# These settings only make the demo's dependent tool sequence deterministic.
130+
# Run-scoped cwd does not require them.
131+
return SandboxAgent(
132+
name=name,
133+
model=model,
134+
instructions=(
135+
"Follow the requested tool sequence exactly. Treat the run working directory as "
136+
"the base for every relative path."
137+
),
138+
capabilities=[Shell(), Filesystem()],
139+
model_settings=ModelSettings(tool_choice="required", parallel_tool_calls=False),
140+
)
141+
142+
143+
async def _run_concurrently(
144+
run_tasks: list[asyncio.Task[RunResult]],
145+
) -> tuple[RunResult, RunResult]:
146+
"""Keep both runs terminal before the caller closes their shared session."""
147+
try:
148+
result_a, result_b = await asyncio.gather(*run_tasks)
149+
except BaseException:
150+
for run_task in run_tasks:
151+
if not run_task.done():
152+
run_task.cancel()
153+
await asyncio.gather(*run_tasks, return_exceptions=True)
154+
raise
155+
return result_a, result_b
156+
157+
158+
# Demo verification. Applications do not need to inspect raw tool calls this way.
159+
160+
161+
def _tool_call_name(item: ToolCallItem) -> str:
162+
raw_item = item.raw_item
163+
if isinstance(raw_item, dict):
164+
type_name = raw_item.get("type")
165+
name = raw_item.get("name")
166+
else:
167+
type_name = getattr(raw_item, "type", None)
168+
name = getattr(raw_item, "name", None)
169+
170+
if type_name == "apply_patch_call":
171+
return "apply_patch"
172+
if isinstance(name, str):
173+
return name
174+
return type_name if isinstance(type_name, str) else ""
175+
176+
177+
def _function_call_arguments(item: ToolCallItem) -> dict[str, object]:
178+
raw_item = item.raw_item
179+
if isinstance(raw_item, dict):
180+
arguments = raw_item.get("arguments")
181+
else:
182+
arguments = getattr(raw_item, "arguments", None)
183+
if not isinstance(arguments, str):
184+
raise RuntimeError(f"{_tool_call_name(item)} did not provide JSON arguments")
185+
186+
try:
187+
parsed = json.loads(arguments)
188+
except json.JSONDecodeError as error:
189+
raise RuntimeError(f"{_tool_call_name(item)} provided invalid JSON arguments") from error
190+
if not isinstance(parsed, dict):
191+
raise RuntimeError(f"{_tool_call_name(item)} arguments were not an object")
192+
return parsed
193+
194+
195+
def _apply_patch_input(item: ToolCallItem) -> str:
196+
raw_item = item.raw_item
197+
if isinstance(raw_item, dict):
198+
raw_input = raw_item.get("input")
199+
else:
200+
raw_input = getattr(raw_item, "input", None)
201+
if not isinstance(raw_input, str):
202+
raise RuntimeError("apply_patch did not provide patch input")
203+
return raw_input
204+
205+
206+
async def _read_workspace_bytes(session: BaseSandboxSession, path: Path) -> bytes:
207+
handle = await session.read(path)
208+
try:
209+
payload = handle.read()
210+
finally:
211+
handle.close()
212+
return payload.encode() if isinstance(payload, str) else bytes(payload)
213+
214+
215+
async def _verify_task(
216+
session: BaseSandboxSession,
217+
*,
218+
task_name: str,
219+
result: RunResult,
220+
) -> None:
221+
color, image_base64 = TASKS[task_name]
222+
task_root = Path("tasks") / task_name
223+
224+
# Direct session operations remain workspace-root-relative, so verification uses full paths.
225+
page = await _read_workspace_bytes(session, task_root / "page.png")
226+
notes = await _read_workspace_bytes(session, task_root / "notes.md")
227+
expected_page = base64.b64decode(image_base64)
228+
expected_notes = f"task={task_name}\nstatus=complete-{task_name}\n".encode()
229+
if page != expected_page:
230+
raise RuntimeError(f"{task_name} copied the wrong relative reference.png")
231+
if notes != expected_notes:
232+
raise RuntimeError(f"{task_name} did not patch its own relative notes.md")
233+
234+
tool_call_items = [item for item in result.new_items if isinstance(item, ToolCallItem)]
235+
tool_calls = [_tool_call_name(item) for item in tool_call_items]
236+
expected_tool_calls = ["exec_command", "view_image", "apply_patch"]
237+
if tool_calls != expected_tool_calls:
238+
raise RuntimeError(
239+
f"{task_name} used {tool_calls}; expected the ordered calls {expected_tool_calls}"
240+
)
241+
242+
shell_arguments = _function_call_arguments(tool_call_items[0])
243+
if shell_arguments.get("cmd") != SHELL_COMMAND or "workdir" in shell_arguments:
244+
raise RuntimeError(f"{task_name} did not use the task-relative shell command")
245+
246+
image_arguments = _function_call_arguments(tool_call_items[1])
247+
if image_arguments.get("path") != "page.png":
248+
raise RuntimeError(f"{task_name} did not view relative page.png")
249+
250+
patch_input = _apply_patch_input(tool_call_items[2])
251+
patch_lines = patch_input.splitlines()
252+
file_directives = [
253+
line
254+
for line in patch_lines
255+
if line.startswith(
256+
("*** Add File: ", "*** Delete File: ", "*** Update File: ", "*** Move to: ")
257+
)
258+
]
259+
expected_old = f"-status=pending-{task_name}"
260+
expected_new = f"+status=complete-{task_name}"
261+
if (
262+
file_directives != ["*** Update File: notes.md"]
263+
or expected_old not in patch_lines
264+
or expected_new not in patch_lines
265+
):
266+
raise RuntimeError(f"{task_name} did not patch relative notes.md with its own marker")
267+
268+
expected_image_url = f"data:image/png;base64,{image_base64}"
269+
image_urls = [
270+
item.output.image_url
271+
for item in result.new_items
272+
if isinstance(item, ToolCallOutputItem) and isinstance(item.output, ToolOutputImage)
273+
]
274+
if expected_image_url not in image_urls:
275+
raise RuntimeError(f"{task_name} viewed an image outside its run working directory")
276+
277+
print(f"\n[{task_name}] cwd={task_root.as_posix()} color={color}")
278+
print(f"tool calls: {', '.join(tool_calls)}")
279+
print(f"notes.md: {notes.decode().strip()}")
280+
print(f"final output: {result.final_output}")
281+
282+
283+
if __name__ == "__main__":
284+
parser = argparse.ArgumentParser(
285+
description="Run two task-local agents concurrently in one live sandbox session."
286+
)
287+
parser.add_argument("--model", default=DEFAULT_MODEL, help="Model name to use.")
288+
args = parser.parse_args()
289+
asyncio.run(main(model=args.model))

‎src/agents/run_config.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import os
44
from collections.abc import Callable
55
from dataclasses import dataclass, field
6+
from pathlib import PurePath
67
from typing import TYPE_CHECKING, Any, Generic, Literal
78

89
from pydantic import TypeAdapter
@@ -218,6 +219,15 @@ class SandboxRunConfig:
218219
Use `SandboxArchiveLimits()` to enable SDK defaults.
219220
"""
220221

222+
cwd: str | PurePath | None = None
223+
"""Optional model-facing working directory relative to the sandbox workspace root.
224+
225+
Relative paths used by the built-in `exec_command`, `view_image`, and `apply_patch` tools
226+
resolve from this directory. Custom path-bearing capabilities must apply their bound
227+
`SandboxWorkspaceScope` explicitly. The directory must already exist when the run starts.
228+
This setting does not change `Manifest.root` or direct `BaseSandboxSession` path behavior.
229+
"""
230+
221231
if TYPE_CHECKING:
222232

223233
def __init__(
@@ -230,9 +240,14 @@ def __init__(
230240
snapshot: SnapshotSpec | SnapshotBase | dict[str, Any] | None = None,
231241
concurrency_limits: SandboxConcurrencyLimits | dict[str, Any] = ...,
232242
archive_limits: SandboxArchiveLimits | dict[str, Any] | None = None,
243+
cwd: str | PurePath | None = None,
233244
) -> None: ...
234245

235246
def __post_init__(self) -> None:
247+
if self.cwd is not None:
248+
from .sandbox.workspace_paths import normalize_sandbox_cwd
249+
250+
self.cwd = normalize_sandbox_cwd(self.cwd).as_posix()
236251
if isinstance(self.manifest, dict):
237252
from .sandbox.manifest import _coerce_manifest
238253

0 commit comments

Comments
 (0)