Backtestsopenai-agents-pythonrun-20261024-184640#4401

Issue #4401 Merged fix PR #4427 Run 24 Oct 2026 · run-20261024-184640 openai/openai-agents-python

[Sandbox] Add a run-scoped cwd across capabilities when reusing a live session

Tie

The judges split evenly between our patch and the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches resolve the issue at its root: each binds a run-scoped cwd onto the per-run cloned capabilities (never mutating session state), defaults shell commands to it, re-bases relative shell workdir, view_image and apply_patch paths beneath it, leaves Manifest.root and direct session calls alone, preserves behavior when cwd is omitted, and renders the working directory in the model instructions. All nine independent tests pass on both, including the concurrent shared-session scenario.

Patch B does this with a small, convention-following change: a `cwd` field on `Capability` with `bind_cwd` mirroring the existing `bind_run_as` pattern, one helper `resolve_path_from_cwd`, cwd validated against the session path policy (rejecting escapes with a clear UserError), the directory auto-created with the run user, Skills/Memory instruction paths rendered absolute so they do not resolve beneath the cwd, and the guide updated where the issue pointed. Its tests cover config normalization, shell workdir resolution, the three tools sharing one base on a real Unix-local session (including the approval callback seeing canonical paths), two concurrent runs with distinct cwds, the no-cwd case, the escape rejection, and Skills/Memory rendering. The whole test module is skipped on Windows, which also skips a few pure unit tests, but the issue's scenarios are Unix-based.

Patch A is more elaborate (a `SandboxWorkspaceScope` abstraction with cwd-relative display paths, lazy-skill path rewriting, stricter cwd validation) and has a broader test suite, but it carries meaningful scope risk beyond the ask: a ~130-line rewrite of custom-tool reconciliation in `run_internal/turn_resolution.py` (the core HITL resume path for all custom tools, not just sandbox), a rework of the runtime's prepared-agent cache keyed on run_as, and a 289-line example. It also validates the cwd by issuing two `session.exec` probes (`test -d`, `test -x`) on every `prepare_agent` call, including the cached path, which adds per-turn round trips on remote sandboxes and depends on a `test` binary. None of that is required by the issue's scenarios (concurrent runs, no approvals), and the core-runner changes are the kind that obscure the fix and add regression risk.

B's minor gaps (root-relative rather than cwd-relative display strings, lazy `load_skill` result path not rewritten) are cosmetic relative to the issue's stated requirements. Weighing correctness as roughly equal, A's tests as stronger but B's as adequate and non-tautological, and B clearly ahead on scope and risk, B is the better fix.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

21m 22s

Wall-clock time in the container

Full test suite

No new failures

2,817 passed · 6 skipped · 2,823 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

496vs 2,719 merged

Changed lines, ours vs merged

Describe the feature

I would like to bind each SandboxAgent run to a logical working directory inside a developer-owned live sandbox, with consistent relative-path behavior across sandbox capabilities.

The SDK currently supports sharing one live sandbox session, but every run uses the session-wide Manifest.root for filesystem path resolution:

  • exec_command(workdir=...) changes the directory for that shell command only.
  • view_image("plot.png") resolves from the session workspace root.
  • apply_patch paths are workspace-root-relative, not relative to the shell workdir.
  • run_as changes the OS identity and permissions, but not path resolution.

This behavior is documented, so I am filing this as a feature request rather than a bug.

Relevant current behavior:

Production use case

Our application runs several trusted document-research agents concurrently. They share the same dependencies and do not require separate containers or security-grade isolation. Each agent only needs a reliable task-local directory:

/workspace/tasks/task-a
/workspace/tasks/task-b

We originally reused one Modal sandbox and assigned each child a task directory. This produced two related problems:

  1. Concurrent children sometimes chose identical workspace-root-relative filenames and overwrote or read each other's files.
  2. After forcing each child's shell commands into its task directory, filesystem capabilities still used the session root.

For example:

exec_command(
    cmd="render input.pdf --output page.png",
    workdir="tasks/task-a",
)

view_image(path="page.png")
# Looks for /workspace/page.png rather than
# /workspace/tasks/task-a/page.png.

apply_patch(path="notes.md", ...)
# Edits /workspace/notes.md rather than
# /workspace/tasks/task-a/notes.md.

We worked around this with capability-specific path-prefixing adapters, task-local temporary directories, and prompt instructions. That remained brittle because every path-bearing capability or custom tool had to implement the convention independently.

We eventually moved to one fresh Modal sandbox per child. That is reliable, but concurrent fan-out now multiplies sandbox startup overhead and active sandbox usage, and we sometimes approach our provider concurrency limits.

Desired behavior

The exact API is not important, but an illustrative shape might be:

run_a = RunConfig(
    sandbox=SandboxRunConfig(
        session=shared_sandbox,
        cwd="tasks/task-a",
    )
)

run_b = RunConfig(
    sandbox=SandboxRunConfig(
        session=shared_sandbox,
        cwd="tasks/task-b",
    )
)

await asyncio.gather(
    Runner.run(agent_a, task_a, run_config=run_a),
    Runner.run(agent_b, task_b, run_config=run_b),
)

For run_a:

  • shell commands without an explicit workdir start under tasks/task-a;
  • a relative shell workdir is interpreted beneath tasks/task-a;
  • view_image("page.png") reads tasks/task-a/page.png;
  • an apply_patch operation on notes.md edits tasks/task-a/notes.md.

The scope should be bound to the run or its prepared capabilities, rather than implemented by mutating session-global cwd or path-policy state. That matters when multiple runs share the session concurrently.

Other desirable properties:

  • Omitting cwd preserves current behavior.
  • Manifest.root, session lifecycle, snapshots, and direct BaseSandboxSession operations remain session-scoped.
  • run_as and filesystem permissions remain orthogonal and continue to compose with the path scope.
  • Built-in workspace-backed capabilities have one consistent relative-path base.
  • The design can support distinct scopes for concurrent runs sharing one developer-owned session.

Minimal model-free reproduction

<details>
<summary>Reproduction using UnixLocalSandboxClient</summary>

import asyncio

from agents.sandbox import Manifest
from agents.sandbox.capabilities.tools import (
    ExecCommandArgs,
    ExecCommandTool,
    ViewImageArgs,
    ViewImageTool,
)
from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient

PNG = (
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0l"
    "EQVR42mP8/x8AAwMCAO+a84QAAAAASUVORK5CYII="
)


async def main() -> None:
    client = UnixLocalSandboxClient()
    session = await client.create(manifest=Manifest())

    try:
        async with session:
            await session.mkdir("tasks/a", parents=True)

            shell = ExecCommandTool(session=session)
            view_image = ViewImageTool(session=session)

            await shell.run(
                ExecCommandArgs(
                    cmd=f"printf '%s' '{PNG}' | base64 -d > plot.png",
                    workdir="tasks/a",
                )
            )

            print(await view_image.run(ViewImageArgs(path="plot.png")))
            print(
                type(
                    await view_image.run(
                        ViewImageArgs(path="tasks/a/plot.png")
                    )
                ).__name__
            )
    finally:
        await client.delete(session)


asyncio.run(main())

Output:

image path `plot.png` was not found
ToolOutputImage

The example uses the Unix-local provider, but our Modal integration encounters the same mismatch.

</details>

Non-goals

  • This does not need to be a chroot or security boundary.
  • It does not replace separate sandboxes for untrusted agents, different images, or genuine compute isolation.
  • It does not require per-run mounts, users, groups, or environments.
  • It does not address child-agent orchestration or result delivery.
  • Deliberate access through absolute paths or .. could remain a separate policy decision; the immediate need is consistent handling of relative paths.

The two patches

Our patch+476 −20
docs/sandbox/guide.mdindex 90abb88c..e5769d6a 100644@@ -235,7 +235,7 @@ Use manifest entries for the material the agent needs before work begins:  Mount entries describe what storage to expose; mount strategies describe how a sandbox backend attaches that storage. See [Sandbox clients](clients.md#mounts-and-remote-storage) for mount options and provider support. -Good manifest design usually means keeping the workspace contract narrow, putting long task recipes in workspace files such as `repo/task.md`, and using relative workspace paths in instructions, for example `repo/task.md` or `output/report.md`. If the agent edits files with the `Filesystem` capability's `apply_patch` tool, remember that patch paths are relative to the sandbox workspace root, not the shell `workdir`.+Good manifest design usually means keeping the workspace contract narrow, putting long task recipes in workspace files such as `repo/task.md`, and using relative workspace paths in instructions, for example `repo/task.md` or `output/report.md`. If the agent edits files with the `Filesystem` capability's `apply_patch` tool, remember that patch paths are relative to the sandbox workspace root (or to `SandboxRunConfig.cwd` when set), not the shell `workdir`.  Use `extra_path_grants` only when the agent needs a concrete absolute path outside the workspace or the manifest needs to copy a trusted local source outside the SDK process working directory. Examples include `/tmp` for temporary tool output, `/opt/toolchain` for a read-only runtime, or a generated skills directory that should be materialized into the sandbox. A grant applies to local source materialization and SDK file APIs. It also applies to shell execution when the backend can enforce filesystem policy: @@ -478,6 +478,8 @@ These options only matter when the runner is creating a fresh sandbox session:  `archive_limits` controls SDK-side resource checks for archive extraction. Set `archive_limits=SandboxArchiveLimits()` to enable the SDK default thresholds, or pass explicit values such as `SandboxArchiveLimits(max_input_bytes=..., max_extracted_bytes=..., max_members=...)` when archives need tighter resource control. Leave `archive_limits=None` to keep the default behavior with no SDK archive resource limits, or set an individual field to `None` to disable only that limit. +`cwd` binds a run to a working directory inside the workspace without changing the session. With `SandboxRunConfig(session=shared_session, cwd="tasks/task-a")`, shell commands without a `workdir` start in `tasks/task-a`, relative shell `workdir` values, `view_image` paths, and `apply_patch` paths resolve beneath it, and the directory is created if it is missing. The value is bound to the run's prepared capabilities (custom capabilities can read `self.cwd`), so concurrent runs that share one live session can each use a different `cwd`. `Manifest.root`, snapshots, direct `BaseSandboxSession` calls, and `run_as` permissions are unchanged. `cwd` must stay inside `Manifest.root`, and it is not a security boundary: absolute paths and `..` segments that stay inside the workspace still work.+ A few implications are worth keeping in mind:  - Fresh sessions: `manifest=` and `snapshot=` only apply when the runner is creating a fresh sandbox session.src/agents/run_config.pyindex 986f62a9..a6ec3b5b 100644@@ -1,8 +1,10 @@ from __future__ import annotations  import os+import posixpath from collections.abc import Callable from dataclasses import dataclass, field+from pathlib import PurePath from typing import TYPE_CHECKING, Any, Generic, Literal  from pydantic import TypeAdapter@@ -186,6 +188,17 @@ class SandboxArchiveLimits:             raise ValueError("archive_limits.max_members must be at least 1")  +def _coerce_sandbox_cwd(value: object) -> str:+    if isinstance(value, PurePath):+        value = value.as_posix()+    if not isinstance(value, str):+        raise TypeError(f"sandbox.cwd must be a string or path, got {type(value).__name__}")+    value = value.replace("\\", "/")+    if not value.strip():+        raise ValueError("sandbox.cwd must not be empty")+    return posixpath.normpath(value)++ @dataclass class SandboxRunConfig:     """Grouped sandbox runtime configuration for `Runner`."""@@ -218,6 +231,17 @@ class SandboxRunConfig:     Use `SandboxArchiveLimits()` to enable SDK defaults.     """ +    cwd: str | None = None+    """Run-scoped working directory for model-facing sandbox capabilities.++    Relative values are interpreted beneath the session's `Manifest.root`; absolute values must+    stay inside it. When set, shell commands without an explicit `workdir` start in this+    directory, relative shell `workdir` values and relative `view_image` / `apply_patch` paths+    resolve beneath it, and the directory is created if missing. The session itself is not+    modified, so concurrent runs sharing one live session can use different values. `None`+    preserves the workspace root as the base for relative paths.+    """+     if TYPE_CHECKING:          def __init__(@@ -230,9 +254,12 @@ class SandboxRunConfig:             snapshot: SnapshotSpec | SnapshotBase | dict[str, Any] | None = None,             concurrency_limits: SandboxConcurrencyLimits | dict[str, Any] = ...,             archive_limits: SandboxArchiveLimits | dict[str, Any] | None = None,+            cwd: str | PurePath | None = None,         ) -> None: ...      def __post_init__(self) -> None:+        if self.cwd is not None:+            self.cwd = _coerce_sandbox_cwd(self.cwd)         if isinstance(self.manifest, dict):             from .sandbox.manifest import _coerce_manifest src/agents/sandbox/apply_patch.pyindex 7f896129..f9fb85e0 100644@@ -14,6 +14,7 @@ from .errors import (     InvalidManifestPathError,     WorkspaceReadNotFoundError, )+from .workspace_paths import resolve_path_from_cwd  if TYPE_CHECKING:     from .session.base_sandbox_session import BaseSandboxSession@@ -38,9 +39,11 @@ class WorkspaceEditor:         session: BaseSandboxSession,         *,         user: str | User | None = None,+        cwd: str | None = None,     ) -> None:         self._session = session         self._user = user+        self._cwd = cwd      async def apply_patch(         self,@@ -144,7 +147,9 @@ class WorkspaceEditor:         # normalizes them. Converting through host-native Path first would make         # backslash handling depend on the SDK host operating system.         try:-            return self._session._workspace_path_policy().relative_path(path)+            return self._session._workspace_path_policy().relative_path(+                resolve_path_from_cwd(path, self._cwd)+            )         except InvalidManifestPathError as exc:             raise ApplyPatchPathError(                 path=path,src/agents/sandbox/capabilities/capability.pyindex e0b16946..c98f28b2 100644@@ -18,6 +18,12 @@ class Capability(BaseModel):     type: str     session: BaseSandboxSession | None = Field(default=None, exclude=True)     run_as: User | None = Field(default=None, exclude=True)+    cwd: str | None = Field(default=None, exclude=True)+    """Run-scoped working directory, relative to the workspace root.++    Model-facing tools should resolve relative paths beneath this directory. `None` means the+    workspace root.+    """      def clone(self) -> "Capability":         """Return a per-run copy of this capability."""@@ -34,6 +40,10 @@ class Capability(BaseModel):         """Bind the sandbox user identity for model-facing operations."""         self.run_as = user +    def bind_cwd(self, cwd: str | None) -> None:+        """Bind the run-scoped working directory for model-facing relative paths."""+        self.cwd = cwd+     def required_capability_types(self) -> set[str]:         """Return capability types that must be present alongside this capability."""         return set()src/agents/sandbox/capabilities/filesystem.pyindex aa023765..fada5b51 100644@@ -32,8 +32,8 @@ class Filesystem(Capability):             raise ValueError("Filesystem capability is not bound to a SandboxSession")          toolset = FilesystemToolSet(-            view_image=ViewImageTool(session=self.session, user=self.run_as),-            apply_patch=SandboxApplyPatchTool(session=self.session, user=self.run_as),+            view_image=ViewImageTool(session=self.session, user=self.run_as, cwd=self.cwd),+            apply_patch=SandboxApplyPatchTool(session=self.session, user=self.run_as, cwd=self.cwd),         )         if self.configure_tools is not None:             self.configure_tools(toolset)src/agents/sandbox/capabilities/memory.pyindex ed9e4824..860da715 100644@@ -1,5 +1,6 @@ from __future__ import annotations +import posixpath from pathlib import Path from typing import Literal, cast @@ -48,7 +49,6 @@ class Memory(Capability):         return {"shell"}      async def instructions(self, manifest: Manifest) -> str | None:-        _ = manifest         if self.read is None:             return None         if self.session is None:@@ -72,8 +72,13 @@ class Memory(Capability):         if not memory_summary:             return None +        memory_dir = self.layout.memories_dir+        if self.cwd is not None:+            # Memory paths are workspace-root-relative; render them absolute so they do not+            # resolve beneath the run-scoped cwd.+            memory_dir = posixpath.join(manifest.root, memory_dir)         return render_memory_read_prompt(-            memory_dir=self.layout.memories_dir,+            memory_dir=memory_dir,             memory_summary=memory_summary,             live_update=self.read.live_update,         )src/agents/sandbox/capabilities/shell.pyindex 44624f6f..ba2aafe2 100644@@ -45,7 +45,7 @@ class Shell(Capability):         if self.session is None:             raise ValueError("Shell capability is not bound to a SandboxSession")         toolset = ShellToolSet(-            exec_command=ExecCommandTool(session=self.session, user=self.run_as),+            exec_command=ExecCommandTool(session=self.session, user=self.run_as, cwd=self.cwd),             write_stdin=WriteStdinTool(session=self.session)             if self.session.supports_pty()             else None,src/agents/sandbox/capabilities/skills.pyindex e68c4375..daa13494 100644@@ -788,6 +788,10 @@ class Skills(Capability):         available_skill_lines: list[str] = []         for skill in skills:             path_str = str(skill.path).replace("\\", "/")+            if self.cwd is not None:+                # Skill paths are workspace-root-relative; render them absolute so they do not+                # resolve beneath the run-scoped cwd.+                path_str = (coerce_posix_path(manifest.root) / path_str).as_posix()             available_skill_lines.append(f"- {skill.name}: {skill.description} (file: {path_str})")          how_to_use_section = (src/agents/sandbox/capabilities/tools/apply_patch_tool.pyindex 1bdba29b..0fe9e4cd 100644@@ -162,10 +162,14 @@ class SandboxApplyPatchTool(CustomTool):         *,         session: BaseSandboxSession,         user: str | User | None = None,+        cwd: str | None = None,         needs_approval: bool | ApplyPatchApprovalFunction = False,         on_approval: ApplyPatchOnApprovalFunction | None = None,     ) -> None:         self.session = session+        # Model-provided paths are re-based beneath `cwd` during normalization, so the editor+        # always receives canonical workspace-root-relative paths.+        self.cwd = cwd         self.editor = SandboxApplyPatchEditor(session, user=user)         super().__init__(             name="apply_patch",@@ -193,7 +197,7 @@ class SandboxApplyPatchTool(CustomTool):         return _parse_custom_tool_input(raw_input)      def _normalize_operation(self, operation: ApplyPatchOperation) -> ApplyPatchOperation:-        return WorkspaceEditor(self.session).normalize_operation(operation)+        return WorkspaceEditor(self.session, cwd=self.cwd).normalize_operation(operation)      def _parse_and_normalize_input(self, raw_input: str) -> list[ApplyPatchOperation]:         return [src/agents/sandbox/capabilities/tools/shell_tool.pyindex 1a0094ad..6c9fc634 100644@@ -15,7 +15,7 @@ from ...errors import ExecTimeoutError, ExecTransportError, PtySessionNotFoundEr from ...session.base_sandbox_session import BaseSandboxSession from ...types import User from ...util.token_truncation import formatted_truncate_text_with_token_count-from ...workspace_paths import sandbox_path_str+from ...workspace_paths import resolve_path_from_cwd, sandbox_path_str  _DEFAULT_EXEC_YIELD_TIME_MS = 10_000 _DEFAULT_WRITE_STDIN_YIELD_TIME_MS = 250@@ -67,12 +67,18 @@ def _normalize_output(stdout: bytes, stderr: bytes) -> str:   def _resolve_workdir_command(-    *, session: BaseSandboxSession, command: str, workdir: str | None+    *,+    session: BaseSandboxSession,+    command: str,+    workdir: str | None,+    cwd: str | None = None, ) -> str:     if workdir is None or workdir.strip() == "":-        return command+        if cwd is None:+            return command+        workdir = "." -    resolved_workdir = session.normalize_path(sandbox_path_str(workdir))+    resolved_workdir = session.normalize_path(resolve_path_from_cwd(sandbox_path_str(workdir), cwd))     return f"cd {shlex.quote(sandbox_path_str(resolved_workdir))} && {command}"  @@ -156,18 +162,22 @@ class ExecCommandTool(FunctionTool):     )     session: BaseSandboxSession = field(init=False, repr=False, compare=False)     user: str | User | None = field(default=None, init=False, repr=False, compare=False)+    cwd: str | None = field(default=None, init=False, repr=False, compare=False)+    """Run-scoped working directory, relative to the workspace root, for relative paths."""      def __init__(         self,         *,         session: BaseSandboxSession,         user: str | User | None = None,+        cwd: str | None = None,         needs_approval: (             bool | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]]         ) = False,     ) -> None:         self.session = session         self.user = user+        self.cwd = cwd         super().__init__(             name=self.tool_name,             description=self.tool_description,@@ -184,7 +194,7 @@ class ExecCommandTool(FunctionTool):         start = time.perf_counter()         timeout_s = args.yield_time_ms / 1000         wrapped_command = _resolve_workdir_command(-            session=self.session, command=args.cmd, workdir=args.workdir+            session=self.session, command=args.cmd, workdir=args.workdir, cwd=self.cwd         )         shell = _resolve_shell(args.shell, args.login)         fallback_notice: str | None = Nonesrc/agents/sandbox/capabilities/tools/view_image.pyindex 6647e074..25fd7ad4 100644@@ -14,7 +14,7 @@ from ....tool import FunctionTool, ToolOutputImage from ...errors import InvalidManifestPathError, WorkspaceReadNotFoundError from ...session.base_sandbox_session import BaseSandboxSession from ...types import User-from ...workspace_paths import sandbox_path_str+from ...workspace_paths import resolve_path_from_cwd, sandbox_path_str  _MAX_IMAGE_BYTES = 10 * 1024 * 1024 _MAX_IMAGE_SIZE_LABEL = "10MB"@@ -82,18 +82,22 @@ class ViewImageTool(FunctionTool):     )     session: BaseSandboxSession = field(init=False, repr=False, compare=False)     user: str | User | None = field(default=None, init=False, repr=False, compare=False)+    cwd: str | None = field(default=None, init=False, repr=False, compare=False)+    """Run-scoped working directory, relative to the workspace root, for relative paths."""      def __init__(         self,         *,         session: BaseSandboxSession,         user: str | User | None = None,+        cwd: str | None = None,         needs_approval: (             bool | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]]         ) = False,     ) -> None:         self.session = session         self.user = user+        self.cwd = cwd         super().__init__(             name=self.tool_name,             description=self.tool_description,@@ -108,9 +112,10 @@ class ViewImageTool(FunctionTool):      async def run(self, args: ViewImageArgs) -> ToolOutputImage | str:         path_policy = self.session._workspace_path_policy()-        resolved_path = path_policy.normalize_path(args.path)+        path = resolve_path_from_cwd(args.path, self.cwd)+        resolved_path = path_policy.normalize_path(path)         try:-            display_path = path_policy.relative_path(args.path).as_posix()+            display_path = path_policy.relative_path(path).as_posix()         except InvalidManifestPathError:             display_path = sandbox_path_str(resolved_path) src/agents/sandbox/runtime.pyindex 0378323a..4e9784cd 100644@@ -22,6 +22,7 @@ from ..run_state import RunState from ..tracing import custom_span, get_current_trace from .capabilities import Capability from .capabilities.memory import Memory+from .errors import InvalidManifestPathError from .memory.manager import SandboxMemoryGenerationManager, get_or_create_memory_generation_manager from .memory.rollouts import (     RolloutTerminalMetadata,@@ -223,6 +224,10 @@ class SandboxRuntime(Generic[TContext]):                     cast(SandboxAgent[TContext], prepared_agent).capabilities,                     _coerce_run_as_user(current_agent.run_as),                 )+                _bind_capability_cwd(+                    cast(SandboxAgent[TContext], prepared_agent).capabilities,+                    self._resolve_run_cwd(session),+                )                 prepared_input = prepare_sandbox_input(                     cast(SandboxAgent[TContext], prepared_agent).capabilities,                     current_input,@@ -238,15 +243,20 @@ class SandboxRuntime(Generic[TContext]):             # Bind before context processing: capabilities may inspect self.session while             # transforming input.             run_as = _coerce_run_as_user(current_agent.run_as)+            cwd = self._resolve_run_cwd(session)+            if cwd is not None:+                await session.mkdir(cwd, parents=True, user=run_as)             for capability in prepared_capabilities:                 capability.bind(session)             _bind_capability_run_as(prepared_capabilities, run_as)+            _bind_capability_cwd(prepared_capabilities, cwd)             prepared_input = prepare_sandbox_input(prepared_capabilities, current_input)             prepared_agent = prepare_sandbox_agent(                 agent=current_agent,                 session=session,                 capabilities=prepared_capabilities,                 run_config_model=self._run_config_model,+                cwd=cwd,             )             self._prepared_agents[id(current_agent)] = prepared_agent             self._prepared_sessions[id(current_agent)] = session@@ -258,6 +268,24 @@ class SandboxRuntime(Generic[TContext]):                 input=prepared_input,             ) +    def _resolve_run_cwd(self, session: BaseSandboxSession) -> str | None:+        """Return the configured run cwd as a workspace-root-relative POSIX path.++        The result is bound onto this run's prepared capabilities only; session-wide path state+        is left untouched so concurrent runs sharing one live session can use different cwds.+        """+        cwd = self._sandbox_config.cwd if self._sandbox_config is not None else None+        if cwd is None:+            return None+        try:+            relative = session._workspace_path_policy().relative_path(cwd).as_posix()+        except InvalidManifestPathError as exc:+            raise UserError(+                f"`SandboxRunConfig.cwd` must stay inside the sandbox workspace root "+                f"`{session.state.manifest.root}`, got `{cwd}`"+            ) from exc+        return None if relative == "." else relative+     async def cleanup(self) -> dict[str, object] | None:         should_trace_cleanup = self.current_session is not None or bool(self._prepared_sessions)         span_cm = (@@ -293,3 +321,8 @@ def _coerce_run_as_user(run_as: User | str | None) -> User | None: def _bind_capability_run_as(capabilities: Sequence[Capability], user: User | None) -> None:     for capability in capabilities:         capability.bind_run_as(user)+++def _bind_capability_cwd(capabilities: Sequence[Capability], cwd: str | None) -> None:+    for capability in capabilities:+        capability.bind_cwd(cwd)src/agents/sandbox/runtime_agent_preparation.pyindex c82f303c..24fce245 100644@@ -1,6 +1,7 @@ from __future__ import annotations  import inspect+import posixpath import textwrap from collections.abc import Awaitable, Callable, Sequence from dataclasses import replace@@ -42,7 +43,7 @@ def clone_capabilities(capabilities: Sequence[Capability]) -> list[Capability]:     return [capability.clone() for capability in capabilities]  -def _filesystem_instructions(manifest: Manifest) -> str:+def _filesystem_instructions(manifest: Manifest, *, cwd: str | None = None) -> str:     header = textwrap.dedent(         """         # Filesystem@@ -55,7 +56,15 @@ def _filesystem_instructions(manifest: Manifest) -> str:         coerce_rel_path=manifest._coerce_rel_path,         depth=3,     ).strip()-    return f"{header}\n\n{tree}"+    sections = [header, tree]+    if cwd is not None:+        cwd_path = posixpath.join(manifest.root, cwd)+        sections.append(+            f"Your working directory for this task is `{cwd_path}`. Shell commands start there, "+            "and relative paths passed to shell `workdir`, `view_image`, and `apply_patch` "+            "resolve from it."+        )+    return "\n\n".join(sections)   def _instruction_section(title: str, body: str) -> str:@@ -68,6 +77,7 @@ def prepare_sandbox_agent(     session: BaseSandboxSession,     capabilities: Sequence[Capability],     run_config_model: str | Model | None = None,+    cwd: str | None = None, ) -> Agent[TContext]:     manifest = session.state.manifest @@ -98,6 +108,7 @@ def prepare_sandbox_agent(             additional_instructions=agent.instructions,             capabilities=capabilities,             manifest=manifest,+            cwd=cwd,         ),         model_settings=replace(             model_settings,@@ -155,6 +166,7 @@ def build_sandbox_instructions(     | None,     capabilities: Sequence[Capability],     manifest: Manifest,+    cwd: str | None = None, ) -> Callable[[RunContextWrapper[TContext], Agent[TContext]], Awaitable[str | None]]:     async def _instructions(         run_context: RunContextWrapper[TContext],@@ -201,7 +213,7 @@ def build_sandbox_instructions(         if remote_mount_policy := build_remote_mount_policy_instructions(manifest):             parts.append(_instruction_section("Sandbox remote mount policy", remote_mount_policy)) -        parts.append(_filesystem_instructions(manifest))+        parts.append(_filesystem_instructions(manifest, cwd=cwd))          return "\n\n".join(parts) if parts else None src/agents/sandbox/workspace_paths.pyindex 4cdc49fe..edbd058c 100644@@ -4,7 +4,7 @@ import os import posixpath import re from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath-from typing import Literal, cast+from typing import Literal, cast, overload  from pydantic import BaseModel, Field, field_validator, model_validator @@ -66,6 +66,31 @@ def sandbox_path_str(path: str | PurePath) -> str:     return coerce_posix_path(path).as_posix()  +@overload+def resolve_path_from_cwd(path: str, cwd: str | PurePath | None) -> str: ...+++@overload+def resolve_path_from_cwd(path: PurePath, cwd: str | PurePath | None) -> str | PurePath: ...+++def resolve_path_from_cwd(path: str | PurePath, cwd: str | PurePath | None) -> str | PurePath:+    """Return ``path`` with a relative path re-based beneath a run-scoped ``cwd``.++    ``cwd`` is interpreted the same way as any other workspace path: relative values are+    relative to the workspace root. Absolute paths (POSIX or Windows) and calls without a+    ``cwd`` are returned unchanged, so the session path policy still decides whether the final+    path is allowed.+    """++    if cwd is None or windows_absolute_path(path) is not None:+        return path+    posix_path = coerce_posix_path(path)+    if posix_path.is_absolute():+        return path+    return (coerce_posix_path(cwd) / posix_path).as_posix()++ def _native_path_from_windows_absolute(path: PureWindowsPath) -> Path | None:     native_path = Path(path)     return native_path if native_path.is_absolute() else Nonetests/sandbox/test_compatibility_guards.pyindex 0e3a2bce..8b3dfdd3 100644@@ -368,6 +368,7 @@ def test_sandbox_dataclass_constructor_field_order_is_stable() -> None:         "snapshot",         "concurrency_limits",         "archive_limits",+        "cwd",     )  tests/sandbox/test_run_cwd.pynew file mode 100644index 00000000..53716d26@@ -0,0 +1,313 @@+from __future__ import annotations++import asyncio+import io+import json+import sys+from collections.abc import Awaitable+from pathlib import Path, PurePosixPath+from typing import Any, cast++import pytest+from openai.types.responses import ResponseCustomToolCall++from agents import Runner+from agents.editor import ApplyPatchOperation+from agents.exceptions import UserError+from agents.items import ToolCallOutputItem+from agents.run import RunConfig+from agents.run_context import RunContextWrapper+from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig+from agents.sandbox.capabilities import Filesystem, Memory, Shell, Skill, Skills+from agents.sandbox.capabilities.tools import (+    ExecCommandArgs,+    ExecCommandTool,+    SandboxApplyPatchTool,+    ViewImageArgs,+    ViewImageTool,+)+from agents.sandbox.capabilities.tools.shell_tool import _resolve_workdir_command+from agents.sandbox.workspace_paths import resolve_path_from_cwd+from agents.testing import ScriptedModel, scripted_sandbox_session+from agents.tool import ToolOutputImage+from tests.test_responses import get_final_output_message, get_function_tool_call++pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="UnixLocalSandbox is Unix-only")++_PNG_B64 = (+    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a84QAAAAASUVORK5CYII="+)+++def _apply_patch_call(call_id: str, patch: str) -> ResponseCustomToolCall:+    return ResponseCustomToolCall(+        type="custom_tool_call",+        name="apply_patch",+        call_id=call_id,+        input=patch,+    )+++async def _create_unix_local_session() -> Any:+    from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient++    client = UnixLocalSandboxClient()+    session = await client.create(manifest=Manifest())+    return client, session+++def test_resolve_path_from_cwd_rebases_only_relative_paths() -> None:+    assert resolve_path_from_cwd("plot.png", None) == "plot.png"+    assert resolve_path_from_cwd("plot.png", "tasks/a") == "tasks/a/plot.png"+    assert resolve_path_from_cwd(r"img\plot.png", "tasks/a") == "tasks/a/img/plot.png"+    assert resolve_path_from_cwd(".", "tasks/a") == "tasks/a"+    assert resolve_path_from_cwd("/tmp/plot.png", "tasks/a") == "/tmp/plot.png"+    assert resolve_path_from_cwd(PurePosixPath("/w/x"), "tasks/a") == PurePosixPath("/w/x")+++def test_sandbox_run_config_normalizes_cwd() -> None:+    assert SandboxRunConfig().cwd is None+    assert SandboxRunConfig(cwd="tasks/a/").cwd == "tasks/a"+    assert SandboxRunConfig(cwd=PurePosixPath("tasks/./b")).cwd == "tasks/b"+    assert SandboxRunConfig(cwd=r"tasks\c").cwd == "tasks/c"+    with pytest.raises(ValueError, match="must not be empty"):+        SandboxRunConfig(cwd="  ")+++def test_shell_workdir_defaults_to_and_resolves_beneath_cwd() -> None:+    session = scripted_sandbox_session(manifest=Manifest(root="/workspace"))++    assert (+        _resolve_workdir_command(session=session, command="pwd", workdir=None, cwd="tasks/a")+        == "cd /workspace/tasks/a && pwd"+    )+    assert (+        _resolve_workdir_command(session=session, command="pwd", workdir="out", cwd="tasks/a")+        == "cd /workspace/tasks/a/out && pwd"+    )+    assert (+        _resolve_workdir_command(+            session=session, command="pwd", workdir="/workspace/other", cwd="tasks/a"+        )+        == "cd /workspace/other && pwd"+    )+    # Without a cwd the command is left to run in the session default directory.+    assert _resolve_workdir_command(session=session, command="pwd", workdir=None) == "pwd"+++@pytest.mark.asyncio+async def test_tools_with_cwd_share_one_relative_path_base_on_unix_local() -> None:+    client, session = await _create_unix_local_session()+    try:+        async with session:+            await session.mkdir("tasks/a", parents=True)+            root = Path(session.state.manifest.root)++            shell = ExecCommandTool(session=session, cwd="tasks/a")+            view_image = ViewImageTool(session=session, cwd="tasks/a")+            apply_patch = SandboxApplyPatchTool(session=session, cwd="tasks/a")++            await shell.run(ExecCommandArgs(cmd=f"printf '%s' '{_PNG_B64}' | base64 -d > plot.png"))+            assert (root / "tasks/a/plot.png").is_file()+            assert not (root / "plot.png").exists()++            assert isinstance(await view_image.run(ViewImageArgs(path="plot.png")), ToolOutputImage)+            # Absolute workspace paths keep working.+            assert isinstance(+                await view_image.run(ViewImageArgs(path=str(root / "tasks/a/plot.png"))),+                ToolOutputImage,+            )++            await shell.run(ExecCommandArgs(cmd="mkdir -p sub && printf x > sub/x.txt"))+            out = await shell.run(ExecCommandArgs(cmd="cat x.txt", workdir="sub"))+            assert out.rstrip().endswith("x")++            seen_paths: list[str] = []++            async def needs_approval(+                _ctx: RunContextWrapper[Any], operation: ApplyPatchOperation, _call_id: str+            ) -> bool:+                seen_paths.append(operation.path)+                return False++            apply_patch.needs_approval = needs_approval+            patch = "*** Begin Patch\n*** Add File: notes.md\n+hello\n*** End Patch\n"+            approval = apply_patch.runtime_needs_approval()+            approval_result = approval(RunContextWrapper(context=None), patch, "call")+            assert await cast(Awaitable[bool], approval_result) is False+            assert seen_paths == ["tasks/a/notes.md"]++            output = await apply_patch.on_invoke_tool(cast(Any, None), patch)+            assert output == "Created tasks/a/notes.md"+            assert (root / "tasks/a/notes.md").read_text() == "hello"+            assert not (root / "notes.md").exists()+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+async def test_concurrent_runs_sharing_live_session_use_distinct_cwds() -> None:+    client, session = await _create_unix_local_session()+    try:+        async with session:+            root = Path(session.state.manifest.root)++            def build_agent(task: str) -> SandboxAgent[Any]:+                model = ScriptedModel(+                    steps=[+                        [+                            get_function_tool_call(+                                "exec_command",+                                json.dumps(+                                    {+                                        "cmd": (+                                            f"printf '%s' '{_PNG_B64}' | base64 -d > page.png "+                                            f"&& printf {task} > who.txt"+                                        )+                                    }+                                ),+                                call_id=f"exec-{task}",+                            )+                        ],+                        [+                            get_function_tool_call(+                                "view_image",+                                json.dumps({"path": "page.png"}),+                                call_id=f"view-{task}",+                            ),+                            _apply_patch_call(+                                f"patch-{task}",+                                "*** Begin Patch\n*** Add File: notes.md\n"+                                f"+{task}\n*** End Patch\n",+                            ),+                        ],+                        [get_final_output_message("done")],+                    ]+                )+                return SandboxAgent(+                    name=f"agent-{task}",+                    model=model,+                    instructions="Work on the task.",+                    capabilities=[Shell(), Filesystem()],+                )++            agent_a = build_agent("a")+            agent_b = build_agent("b")+            result_a, result_b = await asyncio.gather(+                Runner.run(+                    agent_a,+                    "task a",+                    run_config=RunConfig(+                        sandbox=SandboxRunConfig(session=session, cwd="tasks/task-a")+                    ),+                ),+                Runner.run(+                    agent_b,+                    "task b",+                    run_config=RunConfig(+                        sandbox=SandboxRunConfig(session=session, cwd="tasks/task-b")+                    ),+                ),+            )++            for task, result in (("a", result_a), ("b", result_b)):+                task_dir = root / f"tasks/task-{task}"+                assert (task_dir / "who.txt").read_text() == task+                assert (task_dir / "notes.md").read_text() == task+                outputs = [+                    item.output for item in result.new_items if isinstance(item, ToolCallOutputItem)+                ]+                assert any(isinstance(output, ToolOutputImage) for output in outputs), outputs++            assert not (root / "page.png").exists()+            assert not (root / "notes.md").exists()++            model_a = cast(ScriptedModel, agent_a.model)+            instructions = model_a.calls[0].system_instructions or ""+            assert f"`{root.as_posix()}/tasks/task-a`" in instructions+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+async def test_run_without_cwd_keeps_workspace_root_behavior() -> None:+    client, session = await _create_unix_local_session()+    try:+        async with session:+            root = Path(session.state.manifest.root)+            model = ScriptedModel(+                steps=[+                    [+                        _apply_patch_call(+                            "patch",+                            "*** Begin Patch\n*** Add File: notes.md\n+root\n*** End Patch\n",+                        )+                    ],+                    [get_final_output_message("done")],+                ]+            )+            agent = SandboxAgent(name="agent", model=model, capabilities=[Filesystem()])+            await Runner.run(+                agent, "go", run_config=RunConfig(sandbox=SandboxRunConfig(session=session))+            )++            assert (root / "notes.md").read_text() == "root"+            assert "Your working directory" not in (model.calls[0].system_instructions or "")+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+async def test_run_cwd_outside_workspace_root_is_rejected() -> None:+    client, session = await _create_unix_local_session()+    try:+        async with session:+            agent = SandboxAgent(+                name="agent",+                model=ScriptedModel(steps=[[get_final_output_message("done")]]),+                capabilities=[Shell()],+            )+            with pytest.raises(UserError, match="must stay inside the sandbox workspace root"):+                await Runner.run(+                    agent,+                    "go",+                    run_config=RunConfig(sandbox=SandboxRunConfig(session=session, cwd="../out")),+                )+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+async def test_skills_instructions_use_absolute_paths_when_cwd_is_bound() -> None:+    capability = Skills(skills=[Skill(name="my-skill", description="desc", content="literal")])++    instructions = await capability.instructions(Manifest(root="/workspace"))+    assert instructions is not None+    assert "(file: .agents/my-skill)" in instructions++    capability.bind_cwd("tasks/a")+    instructions = await capability.instructions(Manifest(root="/workspace"))+    assert instructions is not None+    assert "(file: /workspace/.agents/my-skill)" in instructions+++@pytest.mark.asyncio+async def test_memory_instructions_use_absolute_paths_when_cwd_is_bound() -> None:+    client, session = await _create_unix_local_session()+    capability = Memory(generate=None)++    try:+        async with session:+            await session.mkdir("memories", parents=True)+            await session.write(Path("memories/memory_summary.md"), io.BytesIO(b"summary"))+            capability.bind(session)+            capability.bind_cwd("tasks/a")++            instructions = await capability.instructions(session.state.manifest)++            assert instructions is not None+            root = session.state.manifest.root+            assert f"{root}/memories/MEMORY.md" in instructions+            assert " memories/MEMORY.md" not in instructions+    finally:+        await client.delete(session) 
Merged fix · PR #4427+2648 −71
examples/sandbox/README.mdindex 733159a06..2248de310 100644@@ -19,6 +19,7 @@ Most examples call a model through `Runner`, so set `OPENAI_API_KEY` in the repo | [`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. | | [`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. | | [`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. |+| [`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. | | [`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. | | [`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. | examples/sandbox/shared_session_workdirs.pynew file mode 100644index 000000000..e21e36281@@ -0,0 +1,289 @@+"""Run two trusted agents in separate working directories of one live sandbox.++Run-scoped working directories make relative paths consistent; they are not confinement.+Use separate sandbox sessions for untrusted agents or workloads that need compute isolation.+"""++from __future__ import annotations++import argparse+import asyncio+import base64+import json+from pathlib import Path++from agents import ModelSettings, Runner, RunResult, ToolOutputImage+from agents.items import ToolCallItem, ToolCallOutputItem+from agents.run import RunConfig+from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig+from agents.sandbox.capabilities import Filesystem, Shell+from agents.sandbox.entries import BaseEntry, Dir, File+from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient+from agents.sandbox.session import BaseSandboxSession+++async def main(*, model: str) -> None:+    client = UnixLocalSandboxClient()+    agent_a = _build_agent(name="Task A worker", model=model)+    agent_b = _build_agent(name="Task B worker", model=model)+    shared_sandbox = await client.create(manifest=_build_manifest())++    try:+        # The session is shared, but each run gets a different base for relative paths.+        run_a_config = RunConfig(+            sandbox=SandboxRunConfig(+                session=shared_sandbox,+                cwd="tasks/task-a",+            ),+            workflow_name="Shared sandbox task A",+        )+        run_b_config = RunConfig(+            sandbox=SandboxRunConfig(+                session=shared_sandbox,+                cwd="tasks/task-b",+            ),+            workflow_name="Shared sandbox task B",+        )++        async with shared_sandbox:+            run_tasks = [+                asyncio.create_task(+                    Runner.run(+                        agent_a,+                        _task_prompt("task-a"),+                        run_config=run_a_config,+                        max_turns=10,+                    )+                ),+                asyncio.create_task(+                    Runner.run(+                        agent_b,+                        _task_prompt("task-b"),+                        run_config=run_b_config,+                        max_turns=10,+                    )+                ),+            ]+            result_a, result_b = await _run_concurrently(run_tasks)++            # These checks make the demo self-verifying; applications do not need them.+            await _verify_task(shared_sandbox, task_name="task-a", result=result_a)+            await _verify_task(shared_sandbox, task_name="task-b", result=result_b)+    finally:+        await client.delete(shared_sandbox)++    print("\nVerified: distinct run-scoped cwd values worked without session-global cwd mutation.")+++# Demo setup. Applications can create task directories and inputs however they prefer.++DEFAULT_MODEL = "gpt-5.6-sol"++# The two task directories intentionally contain the same relative filenames.+TASKS = {+    "task-a": (+        "red",+        "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKklEQVR4nGO4o6ZGU8QwasGoBaMWjFowasGoBaMWjFowasGoBaMWDBULAIjyoD0k0I5JAAAAAElFTkSuQmCC",+    ),+    "task-b": (+        "blue",+        "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKklEQVR4nGNQTX5NU8QwasGoBaMWjFowasGoBaMWjFowasGoBaMWDBULAMMtzEwilX6gAAAAAElFTkSuQmCC",+    ),+}++SHELL_COMMAND = "cp reference.png page.png && cat brief.md"+++def _task_prompt(task_name: str) -> str:+    return f"""+Complete {task_name} in your current run working directory. Use only these relative paths:++1. Call `exec_command` with `{SHELL_COMMAND}`. Do not pass `workdir`.+2. Call `view_image` with `page.png` and identify its color.+3. Use `apply_patch` on `notes.md` to change only `status=pending-{task_name}` to+   `status=complete-{task_name}`.+4. Reply with the task name and image color from the files you inspected.++Do not prefix paths with `tasks/`, use absolute paths, or use the shell to edit `notes.md`.+""".strip()+++def _build_manifest() -> Manifest:+    task_dirs: dict[str | Path, BaseEntry] = {}+    for task_name, (color, image_base64) in TASKS.items():+        task_dirs[task_name] = Dir(+            children={+                "brief.md": File(+                    content=f"# {task_name}\n\nThe reference image is {color}.\n".encode()+                ),+                "reference.png": File(content=base64.b64decode(image_base64)),+                "notes.md": File(+                    content=f"task={task_name}\nstatus=pending-{task_name}\n".encode()+                ),+            }+        )+    return Manifest(entries={"tasks": Dir(children=task_dirs)})+++def _build_agent(*, name: str, model: str) -> SandboxAgent:+    # These settings only make the demo's dependent tool sequence deterministic.+    # Run-scoped cwd does not require them.+    return SandboxAgent(+        name=name,+        model=model,+        instructions=(+            "Follow the requested tool sequence exactly. Treat the run working directory as "+            "the base for every relative path."+        ),+        capabilities=[Shell(), Filesystem()],+        model_settings=ModelSettings(tool_choice="required", parallel_tool_calls=False),+    )+++async def _run_concurrently(+    run_tasks: list[asyncio.Task[RunResult]],+) -> tuple[RunResult, RunResult]:+    """Keep both runs terminal before the caller closes their shared session."""+    try:+        result_a, result_b = await asyncio.gather(*run_tasks)+    except BaseException:+        for run_task in run_tasks:+            if not run_task.done():+                run_task.cancel()+        await asyncio.gather(*run_tasks, return_exceptions=True)+        raise+    return result_a, result_b+++# Demo verification. Applications do not need to inspect raw tool calls this way.+++def _tool_call_name(item: ToolCallItem) -> str:+    raw_item = item.raw_item+    if isinstance(raw_item, dict):+        type_name = raw_item.get("type")+        name = raw_item.get("name")+    else:+        type_name = getattr(raw_item, "type", None)+        name = getattr(raw_item, "name", None)++    if type_name == "apply_patch_call":+        return "apply_patch"+    if isinstance(name, str):+        return name+    return type_name if isinstance(type_name, str) else ""+++def _function_call_arguments(item: ToolCallItem) -> dict[str, object]:+    raw_item = item.raw_item+    if isinstance(raw_item, dict):+        arguments = raw_item.get("arguments")+    else:+        arguments = getattr(raw_item, "arguments", None)+    if not isinstance(arguments, str):+        raise RuntimeError(f"{_tool_call_name(item)} did not provide JSON arguments")++    try:+        parsed = json.loads(arguments)+    except json.JSONDecodeError as error:+        raise RuntimeError(f"{_tool_call_name(item)} provided invalid JSON arguments") from error+    if not isinstance(parsed, dict):+        raise RuntimeError(f"{_tool_call_name(item)} arguments were not an object")+    return parsed+++def _apply_patch_input(item: ToolCallItem) -> str:+    raw_item = item.raw_item+    if isinstance(raw_item, dict):+        raw_input = raw_item.get("input")+    else:+        raw_input = getattr(raw_item, "input", None)+    if not isinstance(raw_input, str):+        raise RuntimeError("apply_patch did not provide patch input")+    return raw_input+++async def _read_workspace_bytes(session: BaseSandboxSession, path: Path) -> bytes:+    handle = await session.read(path)+    try:+        payload = handle.read()+    finally:+        handle.close()+    return payload.encode() if isinstance(payload, str) else bytes(payload)+++async def _verify_task(+    session: BaseSandboxSession,+    *,+    task_name: str,+    result: RunResult,+) -> None:+    color, image_base64 = TASKS[task_name]+    task_root = Path("tasks") / task_name++    # Direct session operations remain workspace-root-relative, so verification uses full paths.+    page = await _read_workspace_bytes(session, task_root / "page.png")+    notes = await _read_workspace_bytes(session, task_root / "notes.md")+    expected_page = base64.b64decode(image_base64)+    expected_notes = f"task={task_name}\nstatus=complete-{task_name}\n".encode()+    if page != expected_page:+        raise RuntimeError(f"{task_name} copied the wrong relative reference.png")+    if notes != expected_notes:+        raise RuntimeError(f"{task_name} did not patch its own relative notes.md")++    tool_call_items = [item for item in result.new_items if isinstance(item, ToolCallItem)]+    tool_calls = [_tool_call_name(item) for item in tool_call_items]+    expected_tool_calls = ["exec_command", "view_image", "apply_patch"]+    if tool_calls != expected_tool_calls:+        raise RuntimeError(+            f"{task_name} used {tool_calls}; expected the ordered calls {expected_tool_calls}"+        )++    shell_arguments = _function_call_arguments(tool_call_items[0])+    if shell_arguments.get("cmd") != SHELL_COMMAND or "workdir" in shell_arguments:+        raise RuntimeError(f"{task_name} did not use the task-relative shell command")++    image_arguments = _function_call_arguments(tool_call_items[1])+    if image_arguments.get("path") != "page.png":+        raise RuntimeError(f"{task_name} did not view relative page.png")++    patch_input = _apply_patch_input(tool_call_items[2])+    patch_lines = patch_input.splitlines()+    file_directives = [+        line+        for line in patch_lines+        if line.startswith(+            ("*** Add File: ", "*** Delete File: ", "*** Update File: ", "*** Move to: ")+        )+    ]+    expected_old = f"-status=pending-{task_name}"+    expected_new = f"+status=complete-{task_name}"+    if (+        file_directives != ["*** Update File: notes.md"]+        or expected_old not in patch_lines+        or expected_new not in patch_lines+    ):+        raise RuntimeError(f"{task_name} did not patch relative notes.md with its own marker")++    expected_image_url = f"data:image/png;base64,{image_base64}"+    image_urls = [+        item.output.image_url+        for item in result.new_items+        if isinstance(item, ToolCallOutputItem) and isinstance(item.output, ToolOutputImage)+    ]+    if expected_image_url not in image_urls:+        raise RuntimeError(f"{task_name} viewed an image outside its run working directory")++    print(f"\n[{task_name}] cwd={task_root.as_posix()} color={color}")+    print(f"tool calls: {', '.join(tool_calls)}")+    print(f"notes.md: {notes.decode().strip()}")+    print(f"final output: {result.final_output}")+++if __name__ == "__main__":+    parser = argparse.ArgumentParser(+        description="Run two task-local agents concurrently in one live sandbox session."+    )+    parser.add_argument("--model", default=DEFAULT_MODEL, help="Model name to use.")+    args = parser.parse_args()+    asyncio.run(main(model=args.model))src/agents/run_config.pyindex 986f62a96..c413910eb 100644@@ -3,6 +3,7 @@ from __future__ import annotations import os from collections.abc import Callable from dataclasses import dataclass, field+from pathlib import PurePath from typing import TYPE_CHECKING, Any, Generic, Literal  from pydantic import TypeAdapter@@ -218,6 +219,15 @@ class SandboxRunConfig:     Use `SandboxArchiveLimits()` to enable SDK defaults.     """ +    cwd: str | PurePath | None = None+    """Optional model-facing working directory relative to the sandbox workspace root.++    Relative paths used by the built-in `exec_command`, `view_image`, and `apply_patch` tools+    resolve from this directory. Custom path-bearing capabilities must apply their bound+    `SandboxWorkspaceScope` explicitly. The directory must already exist when the run starts.+    This setting does not change `Manifest.root` or direct `BaseSandboxSession` path behavior.+    """+     if TYPE_CHECKING:          def __init__(@@ -230,9 +240,14 @@ class SandboxRunConfig:             snapshot: SnapshotSpec | SnapshotBase | dict[str, Any] | None = None,             concurrency_limits: SandboxConcurrencyLimits | dict[str, Any] = ...,             archive_limits: SandboxArchiveLimits | dict[str, Any] | None = None,+            cwd: str | PurePath | None = None,         ) -> None: ...      def __post_init__(self) -> None:+        if self.cwd is not None:+            from .sandbox.workspace_paths import normalize_sandbox_cwd++            self.cwd = normalize_sandbox_cwd(self.cwd).as_posix()         if isinstance(self.manifest, dict):             from .sandbox.manifest import _coerce_manifest src/agents/run_internal/turn_resolution.pyindex b1eead535..ae9fec761 100644@@ -1149,6 +1149,7 @@ async def resolve_interrupted_turn(     """Continue a turn that was previously interrupted waiting for tool approval."""     public_agent = bindings.public_agent     execution_agent = bindings.execution_agent+    output_index = _build_tool_output_index(original_pre_step_items)      current_step = run_state._current_step if run_state is not None else None     if (@@ -1169,6 +1170,14 @@ async def resolve_interrupted_turn(     if (         isinstance(current_step, NextStepInterruption)         and current_step.response_accepted+        and not any(+            get_mapping_or_attr(output, "type") == "custom_tool_call"+            and (+                (call_id := extract_tool_call_id(output)) is None+                or ("custom_tool_call_output", call_id) not in output_index+            )+            for output in new_response.output+        )         and not processed_response.has_tools_or_approvals_to_run()     ):         return await execute_tools_and_side_effects(@@ -1303,8 +1312,6 @@ async def resolve_interrupted_turn(     pending_interruption_keys: set[str] = set()     stable_function_approval_sources: dict[int, ToolApprovalItem] = {} -    output_index = _build_tool_output_index(original_pre_step_items)-     def _has_output_item(call_id: str, expected_type: str) -> bool:         return (expected_type, call_id) in output_index @@ -1846,6 +1853,93 @@ async def resolve_interrupted_turn(         else None     ) +    custom_calls_to_reconcile: list[ResponseCustomToolCall] = []+    custom_call_identities: dict[str, tuple[str, str, str, str]] = {}+    rejected_custom_approvals_by_call_id: dict[+        str,+        tuple[ToolApprovalItem, ResponseCustomToolCall],+    ] = {}++    def _custom_reconciliation_approval(+        call: ResponseCustomToolCall,+        identity: tuple[str, str, str, str],+    ) -> tuple[ToolApprovalItem, bool | None] | None:+        for approval in pending_approval_items:+            if not _approval_matches_agent(approval):+                continue+            if get_mapping_or_attr(approval.raw_item, "type") != "custom_tool_call":+                continue+            if get_tool_approval_item_call_id(approval) != call.call_id:+                continue+            approval_name = get_mapping_or_attr(approval.raw_item, "name")+            if not isinstance(approval_name, str):+                continue+            approval_identity = tool_invocation_identity_and_scope(+                approval.raw_item,+                tool_name=approval_name,+            )+            if approval_identity != identity:+                continue+            return (+                approval,+                context_wrapper.get_approval_status(+                    approval.tool_name or call.name,+                    call.call_id,+                    tool_namespace=approval.tool_namespace,+                    existing_pending=approval,+                ),+            )+        return None++    def _append_custom_reconciliation_call(raw_item: Any) -> None:+        if isinstance(raw_item, ResponseCustomToolCall):+            call = raw_item.model_copy(deep=True)+        elif isinstance(raw_item, Mapping) and raw_item.get("type") == "custom_tool_call":+            try:+                call = ResponseCustomToolCall(**dict(raw_item))+            except Exception as error:+                raise ModelBehaviorError(+                    "Persisted custom tool call is invalid. Start a new run instead of "+                    "resuming this RunState."+                ) from error+        else:+            return++        call_id = extract_tool_call_id(call)+        if call_id is None:+            raise ModelBehaviorError("Custom tool call is missing call_id.")+        identity = tool_invocation_identity_and_scope(call, tool_name=call.name)+        if identity is None:+            raise ModelBehaviorError("Custom tool call has an invalid invocation identity.")+        previous_identity = custom_call_identities.get(call_id)+        if previous_identity is not None:+            if previous_identity != identity:+                raise ModelBehaviorError(+                    "Run state reused a custom tool call ID for different invocations. "+                    "Start a new run instead of resuming this RunState."+                )+            return+        custom_call_identities[call_id] = identity+        if _custom_tool_output_exists(call_id):+            return+        approval_decision = _custom_reconciliation_approval(call, identity)+        if approval_decision is not None:+            approval, approval_status = approval_decision+            if approval_status is False:+                rejected_custom_approvals_by_call_id[call_id] = (approval, call)+                return+            if approval_status is None:+                return+        custom_calls_to_reconcile.append(call)++    for output in new_response.output:+        _append_custom_reconciliation_call(output)+    for custom_run in processed_response.custom_tool_calls:+        _append_custom_reconciliation_call(custom_run.tool_call)+    for approval_item in pending_approval_items:+        if _approval_matches_agent(approval_item):+            _append_custom_reconciliation_call(approval_item.raw_item)+     available_handoffs = await get_handoffs(execution_agent, context_wrapper)     with execution_agent._use_mcp_handoff_snapshot(available_handoffs):         current_tool_inventory = await execution_agent.get_all_tools(context_wrapper)@@ -1915,10 +2009,15 @@ async def resolve_interrupted_turn(      classifier_tools: list[Tool] = [*resolved_function_tools]     classifier_tools.extend(-        tool for tool in resolved_tools if isinstance(tool, ProgrammaticToolCallingTool)+        tool+        for tool in resolved_tools+        if isinstance(tool, ProgrammaticToolCallingTool | CustomTool | ApplyPatchTool)     )     classifier_response = ModelResponse(-        output=cast(Any, [*classifier_context_items, *calls_to_reconcile]),+        output=cast(+            Any,+            [*classifier_context_items, *calls_to_reconcile, *custom_calls_to_reconcile],+        ),         usage=new_response.usage,         response_id=new_response.response_id,         request_id=new_response.request_id,@@ -1938,6 +2037,37 @@ async def resolve_interrupted_turn(     current_functions = {run.tool_call.call_id: run for run in classified.functions}     current_handoffs = {run.tool_call.call_id: run for run in classified.handoffs}     current_missing = {run.tool_call.call_id: run for run in classified.function_tools_not_found}+    processed_response.custom_tool_calls = [+        run+        for run in processed_response.custom_tool_calls+        if _custom_tool_output_exists(_custom_call_id_from_run(run))+    ]+    processed_response.custom_tool_calls.extend(classified.custom_tool_calls)+    rejected_custom_approval_outputs: list[RunItem] = []+    for call_id, (approval, rejected_custom_call) in rejected_custom_approvals_by_call_id.items():+        rejection_message = await resolve_approval_rejection_message(+            context_wrapper=context_wrapper,+            run_config=run_config,+            tool_call=rejected_custom_call,+            tool_type="custom",+            tool_name=approval.tool_name or rejected_custom_call.name,+            call_id=call_id,+            tool_namespace=approval.tool_namespace,+            existing_pending=approval,+        )+        raw_item = {+            "type": "custom_tool_call_output",+            "call_id": call_id,+            "output": rejection_message,+        }+        ItemHelpers.copy_tool_call_caller(rejected_custom_call, raw_item)+        rejected_custom_approval_outputs.append(+            ToolCallOutputItem(+                agent=public_agent,+                output=rejection_message,+                raw_item=cast(Any, raw_item),+            )+        )     pending_nested_transfers: list[tuple[ResponseFunctionToolCall, Any]] = []     pending_nested_drops: list[ResponseFunctionToolCall] = [] @@ -2393,6 +2523,8 @@ async def resolve_interrupted_turn(         append_if_new(shell_rejection)     for custom_tool_rejection in rejected_custom_tool_results:         append_if_new(custom_tool_rejection)+    for custom_tool_rejection in rejected_custom_approval_outputs:+        append_if_new(custom_tool_rejection)     for apply_patch_rejection in rejected_apply_patch_results:         append_if_new(apply_patch_rejection)     for approved_response in plan.approved_mcp_responses:src/agents/sandbox/__init__.pyindex 9dbeb9e3e..841980ab4 100644@@ -26,7 +26,7 @@ from .snapshot import (     resolve_snapshot, ) from .types import ExecResult, ExposedPortEndpoint, FileMode, Group, Permissions, User-from .workspace_paths import SandboxPathGrant+from .workspace_paths import SandboxPathGrant, SandboxWorkspaceScope  __all__ = [     "Capability",@@ -52,6 +52,7 @@ __all__ = [     "SandboxAgent",     "SandboxArchiveLimits",     "SandboxPathGrant",+    "SandboxWorkspaceScope",     "SandboxConcurrencyLimits",     "SandboxError",     "SandboxRunConfig",src/agents/sandbox/apply_patch.pyindex 7f8961299..30623fdf8 100644@@ -14,6 +14,12 @@ from .errors import (     InvalidManifestPathError,     WorkspaceReadNotFoundError, )+from .workspace_paths import (+    SandboxWorkspaceScope,+    _is_absolute_sandbox_path,+    coerce_posix_path,+    posix_path_for_error,+)  if TYPE_CHECKING:     from .session.base_sandbox_session import BaseSandboxSession@@ -38,9 +44,11 @@ class WorkspaceEditor:         session: BaseSandboxSession,         *,         user: str | User | None = None,+        workspace_scope: SandboxWorkspaceScope | None = None,     ) -> None:         self._session = session         self._user = user+        self._workspace_scope = workspace_scope or SandboxWorkspaceScope()      async def apply_patch(         self,@@ -62,9 +70,8 @@ class WorkspaceEditor:         patch_format: PatchFormat | Literal["v4a"] = "v4a",     ) -> ApplyPatchResult:         format_impl = _resolve_patch_format(patch_format)-        relative_path = self._validate_path(operation.path)+        relative_path, display_path = self._resolve_path(operation.path)         destination = self._session.normalize_path(relative_path)-        display_path = relative_path.as_posix()          if operation.type == "delete_file":             await self._ensure_exists(destination, display_path=display_path)@@ -80,7 +87,16 @@ class WorkspaceEditor:             )          if operation.type == "update_file":-            original_text = await self._read_text(destination, op_path=operation.path)+            decode_path = destination+            if self._workspace_scope.cwd is not None:+                decode_path = posix_path_for_error(+                    operation.path if _is_absolute_sandbox_path(operation.path) else display_path+                )+            original_text = await self._read_text(+                destination,+                op_path=operation.path,+                decode_path=decode_path,+            )             try:                 updated_text = format_impl.apply_diff(original_text, operation.diff, mode="default")             except ValueError as exc:@@ -93,12 +109,11 @@ class WorkspaceEditor:                 await self._write_text(destination, updated_text)                 return ApplyPatchResult(output=f"Updated {display_path}") -            moved_relative_path = self._validate_path(operation.move_to)+            moved_relative_path, moved_display_path = self._resolve_path(operation.move_to)             moved_destination = self._session.normalize_path(moved_relative_path)             await self._write_text(moved_destination, updated_text)             if moved_destination != destination:                 await self._session.rm(destination, user=self._user)-            moved_display_path = moved_relative_path.as_posix()             return ApplyPatchResult(                 output=f"Updated {display_path}\nMoved {display_path} to {moved_display_path}"             )@@ -136,6 +151,15 @@ class WorkspaceEditor:             move_to=normalized_move_to,         ) +    def _resolve_path(self, path: str | Path) -> tuple[Path, str]:+        relative_path = self._validate_path(path)+        normalized_path = coerce_posix_path(path)+        display_path = self._workspace_scope.display_path(+            original_path=normalized_path,+            workspace_relative_path=relative_path,+        ).as_posix()+        return relative_path, display_path+     def _validate_path(self, path: str | Path) -> Path:         if isinstance(path, str) and not path.strip():             raise ApplyPatchPathError(path=path, reason="empty")@@ -144,7 +168,9 @@ class WorkspaceEditor:         # normalizes them. Converting through host-native Path first would make         # backslash handling depend on the SDK host operating system.         try:-            return self._session._workspace_path_policy().relative_path(path)+            normalized_path = coerce_posix_path(path)+            scoped_path = self._workspace_scope.anchor(normalized_path)+            return self._session._workspace_path_policy().relative_path(scoped_path)         except InvalidManifestPathError as exc:             raise ApplyPatchPathError(                 path=path,@@ -160,7 +186,7 @@ class WorkspaceEditor:         else:             handle.close() -    async def _read_text(self, destination: Path, *, op_path: str) -> str:+    async def _read_text(self, destination: Path, *, op_path: str, decode_path: Path) -> str:         try:             handle = await self._session.read(destination, user=self._user)         except (FileNotFoundError, WorkspaceReadNotFoundError) as exc:@@ -177,7 +203,7 @@ class WorkspaceEditor:             try:                 return bytes(payload).decode("utf-8")             except UnicodeDecodeError as exc:-                raise ApplyPatchDecodeError(path=destination, cause=exc) from exc+                raise ApplyPatchDecodeError(path=decode_path, cause=exc) from exc         raise ApplyPatchDiffError(             message=f"apply_patch read() returned non-text content: {type(payload).__name__}",             path=op_path,src/agents/sandbox/capabilities/capability.pyindex e0b169463..b3e702961 100644@@ -10,6 +10,7 @@ from ...tool import FunctionTool, Tool from ..manifest import Manifest from ..session.base_sandbox_session import BaseSandboxSession from ..types import User+from ..workspace_paths import SandboxWorkspaceScope   class Capability(BaseModel):@@ -18,6 +19,11 @@ class Capability(BaseModel):     type: str     session: BaseSandboxSession | None = Field(default=None, exclude=True)     run_as: User | None = Field(default=None, exclude=True)+    workspace_scope: SandboxWorkspaceScope = Field(+        default_factory=SandboxWorkspaceScope,+        exclude=True,+        repr=False,+    )      def clone(self) -> "Capability":         """Return a per-run copy of this capability."""@@ -34,6 +40,10 @@ class Capability(BaseModel):         """Bind the sandbox user identity for model-facing operations."""         self.run_as = user +    def bind_workspace_scope(self, scope: SandboxWorkspaceScope) -> None:+        """Bind the immutable model-facing path scope for this run."""+        self.workspace_scope = scope+     def required_capability_types(self) -> set[str]:         """Return capability types that must be present alongside this capability."""         return set()@@ -65,6 +75,7 @@ def _clone_capability_value(value: Any) -> Any:     if isinstance(         value,         BaseSandboxSession+        | SandboxWorkspaceScope         | asyncio.Event         | asyncio.Lock         | asyncio.Semaphoresrc/agents/sandbox/capabilities/filesystem.pyindex aa023765f..0a04d6baa 100644@@ -1,12 +1,13 @@ from __future__ import annotations  from collections.abc import Callable-from dataclasses import dataclass+from dataclasses import dataclass, field from typing import Literal  from pydantic import Field  from ...tool import Tool+from ..workspace_paths import SandboxWorkspaceScope from .capability import Capability from .tools import SandboxApplyPatchTool, ViewImageTool @@ -17,6 +18,7 @@ class FilesystemToolSet:      view_image: ViewImageTool     apply_patch: SandboxApplyPatchTool+    workspace_scope: SandboxWorkspaceScope = field(default_factory=SandboxWorkspaceScope)   FilesystemToolConfigurator = Callable[[FilesystemToolSet], None]@@ -32,8 +34,17 @@ class Filesystem(Capability):             raise ValueError("Filesystem capability is not bound to a SandboxSession")          toolset = FilesystemToolSet(-            view_image=ViewImageTool(session=self.session, user=self.run_as),-            apply_patch=SandboxApplyPatchTool(session=self.session, user=self.run_as),+            view_image=ViewImageTool(+                session=self.session,+                user=self.run_as,+                workspace_scope=self.workspace_scope,+            ),+            apply_patch=SandboxApplyPatchTool(+                session=self.session,+                user=self.run_as,+                workspace_scope=self.workspace_scope,+            ),+            workspace_scope=self.workspace_scope,         )         if self.configure_tools is not None:             self.configure_tools(toolset)src/agents/sandbox/capabilities/memory.pyindex ed9e48247..cb0810ca2 100644@@ -54,7 +54,8 @@ class Memory(Capability):         if self.session is None:             raise ValueError("Memory capability is not bound to a SandboxSession") -        memory_summary_path = Path(self.layout.memories_dir) / "memory_summary.md"+        memory_dir_path = Path(self.layout.memories_dir)+        memory_summary_path = memory_dir_path / "memory_summary.md"         try:             handle = await self.session.read(memory_summary_path, user=self.run_as)         except WorkspaceReadNotFoundError:@@ -72,8 +73,16 @@ class Memory(Capability):         if not memory_summary:             return None +        model_memory_dir = (+            self.layout.memories_dir+            if self.workspace_scope.cwd is None+            else self.workspace_scope.model_resource_path(+                workspace_root=manifest.root,+                workspace_relative_path=memory_dir_path,+            ).as_posix()+        )         return render_memory_read_prompt(-            memory_dir=self.layout.memories_dir,+            memory_dir=model_memory_dir,             memory_summary=memory_summary,             live_update=self.read.live_update,         )src/agents/sandbox/capabilities/shell.pyindex 44624f6f3..b753c5f7e 100644@@ -9,6 +9,7 @@ from pydantic import Field  from ...tool import Tool from ..manifest import Manifest+from ..workspace_paths import SandboxWorkspaceScope from .capability import Capability from .tools import ExecCommandTool, WriteStdinTool @@ -31,6 +32,7 @@ class ShellToolSet:      exec_command: ExecCommandTool     write_stdin: WriteStdinTool | None+    workspace_scope: SandboxWorkspaceScope = SandboxWorkspaceScope()   ShellToolConfigurator = Callable[[ShellToolSet], None]@@ -45,10 +47,15 @@ class Shell(Capability):         if self.session is None:             raise ValueError("Shell capability is not bound to a SandboxSession")         toolset = ShellToolSet(-            exec_command=ExecCommandTool(session=self.session, user=self.run_as),+            exec_command=ExecCommandTool(+                session=self.session,+                user=self.run_as,+                workspace_scope=self.workspace_scope,+            ),             write_stdin=WriteStdinTool(session=self.session)             if self.session.supports_pty()             else None,+            workspace_scope=self.workspace_scope,         )         if self.configure_tools is not None:             self.configure_tools(toolset)src/agents/sandbox/capabilities/skills.pyindex e68c43755..b46a3468d 100644@@ -5,7 +5,7 @@ import io import stat from collections.abc import Mapping, Sequence from dataclasses import dataclass, field-from pathlib import Path+from pathlib import Path, PurePath from typing import Any, Literal  from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator@@ -31,6 +31,20 @@ _SKILLS_SECTION_INTRO = (     "and file path so you can open the source for full instructions when using a specific skill." ) +_SKILL_PATH_GUIDANCE = (+    "- Skill paths: Treat each listed path as the skill root. Resolve relative paths in "+    "`SKILL.md`, including `scripts/`, `references/`, and `assets/`, against that root rather "+    "than the shell working directory.",+    "- Shared resources: Skill files belong to the sandbox session and may be visible to other "+    "runs. Unless the task explicitly requires editing a skill, invoke scripts through the "+    "listed skill root and write task inputs, outputs, caches, and temporary files in the run "+    "working directory.",+)++_SCOPED_SKILL_PATH_ERROR = (+    "skill path must be non-empty and workspace-relative when sandbox.cwd is configured"+)+ _HOW_TO_USE_SKILLS_SECTION = "\n".join(     [         "### How to use skills",@@ -666,6 +680,32 @@ class Skills(Capability):             raise ValueError(f"{type(self).__name__} is not bound to a SandboxSession")         return [_LoadSkillTool(skills=self)] +    def _model_skill_path(+        self,+        *,+        manifest: Manifest,+        skill_name: str,+        path: str | PurePath,+    ) -> str:+        if self.workspace_scope.cwd is None:+            return str(path).replace("\\", "/")+        try:+            return self.workspace_scope.model_resource_path(+                workspace_root=manifest.root,+                workspace_relative_path=path,+            ).as_posix()+        except ValueError as exc:+            raise SkillsConfigError(+                message=_SCOPED_SKILL_PATH_ERROR,+                context={+                    "skill_name": skill_name,+                    "field": "path",+                    "path": path.as_posix() if isinstance(path, PurePath) else path,+                    "reason": "invalid",+                },+                cause=exc,+            ) from exc+     async def load_skill(self, skill_name: str) -> dict[str, str]:         if self.lazy_from is None:             raise SkillsConfigError(@@ -674,12 +714,29 @@ class Skills(Capability):             )         if self.session is None:             raise ValueError(f"{type(self).__name__} is not bound to a SandboxSession")-        return await self.lazy_from.load_skill(+        result = await self.lazy_from.load_skill(             skill_name=skill_name,             session=self.session,             skills_path=self.skills_path,             user=self.run_as,         )+        if self.workspace_scope.cwd is None:+            return result++        source_path = result.get("path")+        if source_path is None:+            raise SkillsConfigError(+                message=_SCOPED_SKILL_PATH_ERROR,+                context={"skill_name": skill_name, "field": "path", "reason": "missing"},+            )+        return {+            **result,+            "path": self._model_skill_path(+                manifest=self.session.state.manifest,+                skill_name=skill_name,+                path=source_path,+            ),+        }      async def _resolve_runtime_metadata(self, manifest: Manifest) -> list[SkillMetadata]:         if self.session is None:@@ -787,7 +844,11 @@ class Skills(Capability):          available_skill_lines: list[str] = []         for skill in skills:-            path_str = str(skill.path).replace("\\", "/")+            path_str = self._model_skill_path(+                manifest=manifest,+                skill_name=skill.name,+                path=skill.path,+            )             available_skill_lines.append(f"- {skill.name}: {skill.description} (file: {path_str})")          how_to_use_section = (@@ -801,6 +862,11 @@ class Skills(Capability):                 _SKILLS_SECTION_INTRO,                 "### Available skills",                 *available_skill_lines,+                *(+                    ["### Run-scoped skill paths", *_SKILL_PATH_GUIDANCE]+                    if self.workspace_scope.cwd is not None+                    else []+                ),                 *(                     [                         "### Lazy loading",src/agents/sandbox/capabilities/tools/apply_patch_tool.pyindex 1bdba29bd..6bfeeb416 100644@@ -18,6 +18,7 @@ from ...apply_patch import WorkspaceEditor from ...errors import ApplyPatchPathError from ...session.base_sandbox_session import BaseSandboxSession from ...types import User+from ...workspace_paths import SandboxWorkspaceScope  _APPLY_PATCH_CUSTOM_TOOL_GRAMMAR = r""" start: begin_patch hunk+ end_patch@@ -137,18 +138,37 @@ _MOVE_TO = "*** Move to: "   class SandboxApplyPatchEditor(ApplyPatchEditor):-    def __init__(self, session: BaseSandboxSession, *, user: str | User | None = None) -> None:+    def __init__(+        self,+        session: BaseSandboxSession,+        *,+        user: str | User | None = None,+        workspace_scope: SandboxWorkspaceScope | None = None,+    ) -> None:         self.session = session         self.user = user+        self.workspace_scope = workspace_scope or SandboxWorkspaceScope()      async def create_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:-        return await WorkspaceEditor(self.session, user=self.user).apply_operation(operation)+        return await WorkspaceEditor(+            self.session,+            user=self.user,+            workspace_scope=self.workspace_scope,+        ).apply_operation(operation)      async def update_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:-        return await WorkspaceEditor(self.session, user=self.user).apply_operation(operation)+        return await WorkspaceEditor(+            self.session,+            user=self.user,+            workspace_scope=self.workspace_scope,+        ).apply_operation(operation)      async def delete_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:-        return await WorkspaceEditor(self.session, user=self.user).apply_operation(operation)+        return await WorkspaceEditor(+            self.session,+            user=self.user,+            workspace_scope=self.workspace_scope,+        ).apply_operation(operation)   class SandboxApplyPatchTool(CustomTool):@@ -164,9 +184,15 @@ class SandboxApplyPatchTool(CustomTool):         user: str | User | None = None,         needs_approval: bool | ApplyPatchApprovalFunction = False,         on_approval: ApplyPatchOnApprovalFunction | None = None,+        workspace_scope: SandboxWorkspaceScope | None = None,     ) -> None:         self.session = session-        self.editor = SandboxApplyPatchEditor(session, user=user)+        self.workspace_scope = workspace_scope or SandboxWorkspaceScope()+        self.editor = SandboxApplyPatchEditor(+            session,+            user=user,+            workspace_scope=self.workspace_scope,+        )         super().__init__(             name="apply_patch",             description=_APPLY_PATCH_CUSTOM_TOOL_DESCRIPTION,@@ -193,7 +219,10 @@ class SandboxApplyPatchTool(CustomTool):         return _parse_custom_tool_input(raw_input)      def _normalize_operation(self, operation: ApplyPatchOperation) -> ApplyPatchOperation:-        return WorkspaceEditor(self.session).normalize_operation(operation)+        return WorkspaceEditor(+            self.session,+            workspace_scope=self.workspace_scope,+        ).normalize_operation(operation)      def _parse_and_normalize_input(self, raw_input: str) -> list[ApplyPatchOperation]:         return [@@ -223,9 +252,12 @@ class SandboxApplyPatchTool(CustomTool):         return False      async def _on_invoke_tool(self, ctx: ToolContext[Any], raw_input: str) -> str:-        # Normalize every operation before executing any of them. This prevents a valid-        # prefix from mutating the workspace when a later path is invalid.-        operations = self._parse_and_normalize_input(raw_input)+        operations = self.parse_custom_input(raw_input)+        # Validate every operation before executing any of them. Keep the raw paths for+        # execution so an absolute model path does not lose its identity before the scoped+        # editor applies the run cwd.+        for operation in operations:+            self._normalize_operation(operation)          operation_outputs: list[str] = []         for operation in operations:src/agents/sandbox/capabilities/tools/shell_tool.pyindex 1a0094adf..3b6df7646 100644@@ -15,7 +15,7 @@ from ...errors import ExecTimeoutError, ExecTransportError, PtySessionNotFoundEr from ...session.base_sandbox_session import BaseSandboxSession from ...types import User from ...util.token_truncation import formatted_truncate_text_with_token_count-from ...workspace_paths import sandbox_path_str+from ...workspace_paths import SandboxWorkspaceScope, coerce_posix_path, sandbox_path_str  _DEFAULT_EXEC_YIELD_TIME_MS = 10_000 _DEFAULT_WRITE_STDIN_YIELD_TIME_MS = 250@@ -67,12 +67,21 @@ def _normalize_output(stdout: bytes, stderr: bytes) -> str:   def _resolve_workdir_command(-    *, session: BaseSandboxSession, command: str, workdir: str | None+    *,+    session: BaseSandboxSession,+    workspace_scope: SandboxWorkspaceScope | None = None,+    command: str,+    workdir: str | None, ) -> str:+    workspace_scope = workspace_scope or SandboxWorkspaceScope()     if workdir is None or workdir.strip() == "":-        return command+        if workspace_scope.cwd is None:+            return command+        workdir = "." -    resolved_workdir = session.normalize_path(sandbox_path_str(workdir))+    resolved_workdir = session.normalize_path(+        sandbox_path_str(workspace_scope.anchor(coerce_posix_path(workdir)))+    )     return f"cd {shlex.quote(sandbox_path_str(resolved_workdir))} && {command}"  @@ -156,6 +165,12 @@ class ExecCommandTool(FunctionTool):     )     session: BaseSandboxSession = field(init=False, repr=False, compare=False)     user: str | User | None = field(default=None, init=False, repr=False, compare=False)+    workspace_scope: SandboxWorkspaceScope = field(+        default_factory=SandboxWorkspaceScope,+        init=False,+        repr=False,+        compare=False,+    )      def __init__(         self,@@ -165,9 +180,11 @@ class ExecCommandTool(FunctionTool):         needs_approval: (             bool | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]]         ) = False,+        workspace_scope: SandboxWorkspaceScope | None = None,     ) -> None:         self.session = session         self.user = user+        self.workspace_scope = workspace_scope or SandboxWorkspaceScope()         super().__init__(             name=self.tool_name,             description=self.tool_description,@@ -184,7 +201,10 @@ class ExecCommandTool(FunctionTool):         start = time.perf_counter()         timeout_s = args.yield_time_ms / 1000         wrapped_command = _resolve_workdir_command(-            session=self.session, command=args.cmd, workdir=args.workdir+            session=self.session,+            workspace_scope=self.workspace_scope,+            command=args.cmd,+            workdir=args.workdir,         )         shell = _resolve_shell(args.shell, args.login)         fallback_notice: str | None = Nonesrc/agents/sandbox/capabilities/tools/view_image.pyindex 6647e074a..fb8d47535 100644@@ -14,7 +14,7 @@ from ....tool import FunctionTool, ToolOutputImage from ...errors import InvalidManifestPathError, WorkspaceReadNotFoundError from ...session.base_sandbox_session import BaseSandboxSession from ...types import User-from ...workspace_paths import sandbox_path_str+from ...workspace_paths import SandboxWorkspaceScope, coerce_posix_path, sandbox_path_str  _MAX_IMAGE_BYTES = 10 * 1024 * 1024 _MAX_IMAGE_SIZE_LABEL = "10MB"@@ -82,6 +82,12 @@ class ViewImageTool(FunctionTool):     )     session: BaseSandboxSession = field(init=False, repr=False, compare=False)     user: str | User | None = field(default=None, init=False, repr=False, compare=False)+    workspace_scope: SandboxWorkspaceScope = field(+        default_factory=SandboxWorkspaceScope,+        init=False,+        repr=False,+        compare=False,+    )      def __init__(         self,@@ -91,9 +97,11 @@ class ViewImageTool(FunctionTool):         needs_approval: (             bool | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]]         ) = False,+        workspace_scope: SandboxWorkspaceScope | None = None,     ) -> None:         self.session = session         self.user = user+        self.workspace_scope = workspace_scope or SandboxWorkspaceScope()         super().__init__(             name=self.tool_name,             description=self.tool_description,@@ -107,10 +115,16 @@ class ViewImageTool(FunctionTool):         return await self.run(self.args_model.model_validate_json(raw_input))      async def run(self, args: ViewImageArgs) -> ToolOutputImage | str:+        input_path = args.path+        scoped_path = self.workspace_scope.anchor(coerce_posix_path(input_path))         path_policy = self.session._workspace_path_policy()-        resolved_path = path_policy.normalize_path(args.path)+        resolved_path = path_policy.normalize_path(scoped_path)         try:-            display_path = path_policy.relative_path(args.path).as_posix()+            workspace_relative_path = path_policy.relative_path(scoped_path)+            display_path = self.workspace_scope.display_path(+                original_path=scoped_path,+                workspace_relative_path=workspace_relative_path,+            ).as_posix()         except InvalidManifestPathError:             display_path = sandbox_path_str(resolved_path) src/agents/sandbox/runtime.pyindex 0378323a6..4927aa239 100644@@ -4,6 +4,7 @@ import logging from collections.abc import Sequence from contextlib import nullcontext from dataclasses import dataclass+from pathlib import Path from typing import Any, Generic, cast  from ..agent import Agent@@ -36,6 +37,7 @@ from .runtime_session_manager import SandboxRuntimeSessionManager from .sandbox_agent import SandboxAgent from .session.base_sandbox_session import BaseSandboxSession from .types import User+from .workspace_paths import SandboxWorkspaceScope, sandbox_path_str  logger = logging.getLogger(__name__) @@ -46,6 +48,13 @@ class _SandboxPreparedAgent(Generic[TContext]):     input: str | list[TResponseInputItem]  +@dataclass+class _SandboxPreparedAgentCache(Generic[TContext]):+    agent: Agent[TContext]+    session: BaseSandboxSession+    run_as_name: str | None++ def _supports_trace_spans() -> bool:     current_trace = get_current_trace()     return current_trace is not None and current_trace.export() is not None@@ -74,6 +83,9 @@ class SandboxRuntime(Generic[TContext]):     ) -> None:         self._sandbox_config = run_config.sandbox if run_config is not None else None         self._run_config_model = run_config.model if run_config is not None else None+        self._workspace_scope = SandboxWorkspaceScope.from_cwd(+            self._sandbox_config.cwd if self._sandbox_config is not None else None+        )         # The runner resolves this before constructing the runtime. It can be None only when         # sandbox is disabled or tests instantiate the runtime directly.         self._rollout_id = rollout_id@@ -83,8 +95,7 @@ class SandboxRuntime(Generic[TContext]):             sandbox_config=self._sandbox_config,             run_state=run_state,         )-        self._prepared_agents: dict[int, Agent[TContext]] = {}-        self._prepared_sessions: dict[int, BaseSandboxSession] = {}+        self._prepared_agents: dict[int, _SandboxPreparedAgentCache[TContext]] = {}      @property     def enabled(self) -> bool:@@ -206,27 +217,45 @@ class SandboxRuntime(Generic[TContext]):         )         with span_cm:             self._session_manager.acquire_agent(current_agent)-            prepared_agent = self._prepared_agents.get(id(current_agent))+            cached_preparation = self._prepared_agents.get(id(current_agent))             prepared_capabilities = clone_capabilities(current_agent.capabilities)             session = await self._session_manager.ensure_session(                 agent=current_agent,                 capabilities=prepared_capabilities,                 is_resumed_state=is_resumed_state,             )-            if (-                prepared_agent is not None-                and self._prepared_sessions.get(id(current_agent)) is session-            ):+            run_as = _coerce_run_as_user(current_agent.run_as)+            await _validate_workspace_scope(+                session=session,+                scope=self._workspace_scope,+                run_as=run_as,+            )+            prepared_agent: Agent[TContext]+            if cached_preparation is not None and cached_preparation.session is session:                 # Reuse the cached execution agent's bound capability instances so context                 # processing can depend on live session state and preserve per-run state.-                _bind_capability_run_as(-                    cast(SandboxAgent[TContext], prepared_agent).capabilities,-                    _coerce_run_as_user(current_agent.run_as),-                )+                cached_agent = cast(SandboxAgent[TContext], cached_preparation.agent)+                prepared_agent = cached_agent+                cached_capabilities = cached_agent.capabilities+                _bind_capability_run_as(cached_capabilities, run_as)                 prepared_input = prepare_sandbox_input(-                    cast(SandboxAgent[TContext], prepared_agent).capabilities,+                    cached_capabilities,                     current_input,                 )+                run_as_name = run_as.name if run_as is not None else None+                if cached_preparation.run_as_name != run_as_name:+                    prepared_agent = prepare_sandbox_agent(+                        agent=current_agent,+                        session=session,+                        capabilities=cached_capabilities,+                        run_config_model=self._run_config_model,+                        workspace_scope=self._workspace_scope,+                    )+                    self._prepared_agents[id(current_agent)] = _SandboxPreparedAgentCache(+                        agent=prepared_agent,+                        session=session,+                        run_as_name=run_as_name,+                    )                 return _SandboxPreparedAgent(                     bindings=bind_execution_agent(                         public_agent=current_agent,@@ -237,9 +266,9 @@ class SandboxRuntime(Generic[TContext]):              # Bind before context processing: capabilities may inspect self.session while             # transforming input.-            run_as = _coerce_run_as_user(current_agent.run_as)             for capability in prepared_capabilities:                 capability.bind(session)+                capability.bind_workspace_scope(self._workspace_scope)             _bind_capability_run_as(prepared_capabilities, run_as)             prepared_input = prepare_sandbox_input(prepared_capabilities, current_input)             prepared_agent = prepare_sandbox_agent(@@ -247,9 +276,13 @@ class SandboxRuntime(Generic[TContext]):                 session=session,                 capabilities=prepared_capabilities,                 run_config_model=self._run_config_model,+                workspace_scope=self._workspace_scope,+            )+            self._prepared_agents[id(current_agent)] = _SandboxPreparedAgentCache(+                agent=prepared_agent,+                session=session,+                run_as_name=run_as.name if run_as is not None else None,             )-            self._prepared_agents[id(current_agent)] = prepared_agent-            self._prepared_sessions[id(current_agent)] = session             return _SandboxPreparedAgent(                 bindings=bind_execution_agent(                     public_agent=current_agent,@@ -259,7 +292,7 @@ class SandboxRuntime(Generic[TContext]):             )      async def cleanup(self) -> dict[str, object] | None:-        should_trace_cleanup = self.current_session is not None or bool(self._prepared_sessions)+        should_trace_cleanup = self.current_session is not None or bool(self._prepared_agents)         span_cm = (             custom_span("sandbox.cleanup", data={})             if should_trace_cleanup and _supports_trace_spans()@@ -270,7 +303,6 @@ class SandboxRuntime(Generic[TContext]):                 return await self._session_manager.cleanup()             finally:                 self._prepared_agents.clear()-                self._prepared_sessions.clear()   def _get_memory_capability(agent: Agent[TContext]) -> Memory | None:@@ -293,3 +325,29 @@ def _coerce_run_as_user(run_as: User | str | None) -> User | None: def _bind_capability_run_as(capabilities: Sequence[Capability], user: User | None) -> None:     for capability in capabilities:         capability.bind_run_as(user)+++async def _validate_workspace_scope(+    *,+    session: BaseSandboxSession,+    scope: SandboxWorkspaceScope,+    run_as: User | None,+) -> None:+    cwd = scope.cwd+    if cwd is None:+        return++    resolved_cwd = sandbox_path_str(session.normalize_path(cast(Path | str, scope.anchor("."))))+    for test_flag in ("-d", "-x"):+        result = await session.exec(+            "test",+            test_flag,+            resolved_cwd,+            shell=False,+            user=run_as,+        )+        if not result.ok():+            raise UserError(+                f"Sandbox working directory `{sandbox_path_str(cwd)}` does not exist or is not "+                "accessible for the configured sandbox user"+            )src/agents/sandbox/runtime_agent_preparation.pyindex c82f303ca..841c43d07 100644@@ -22,6 +22,7 @@ from .remote_mount_policy import build_remote_mount_policy_instructions from .sandbox_agent import SandboxAgent from .session.base_sandbox_session import BaseSandboxSession from .util.deep_merge import deep_merge+from .workspace_paths import SandboxWorkspaceScope, coerce_posix_path   @lru_cache(maxsize=1)@@ -42,13 +43,33 @@ def clone_capabilities(capabilities: Sequence[Capability]) -> list[Capability]:     return [capability.clone() for capability in capabilities]  -def _filesystem_instructions(manifest: Manifest) -> str:+def _filesystem_instructions(+    manifest: Manifest,+    workspace_scope: SandboxWorkspaceScope | None = None,+) -> str:+    effective_workspace_scope = workspace_scope or SandboxWorkspaceScope()     header = textwrap.dedent(         """         # Filesystem         You have access to a container with a filesystem. The filesystem layout is:         """     ).strip()+    if effective_workspace_scope.cwd is not None:+        workspace_root = coerce_posix_path(manifest.root)+        working_directory = workspace_root / effective_workspace_scope.cwd+        header = "\n".join(+            [+                header,+                f"For this run, the working directory is `{working_directory.as_posix()}`.",+                "Relative paths passed to the built-in `exec_command`, `view_image`, and "+                "`apply_patch` tools resolve from this directory.",+                "Other sandbox tools follow their own path contract.",+                f"The session workspace root remains `{workspace_root.as_posix()}`.",+                "The working directory changes path resolution; it does not isolate this run "+                "from the rest of the session workspace.",+                "Files outside the working directory may be visible to or shared with other runs.",+            ]+        )     tree = render_manifest_description(         root=manifest.root,         entries=manifest.validated_entries(),@@ -68,8 +89,10 @@ def prepare_sandbox_agent(     session: BaseSandboxSession,     capabilities: Sequence[Capability],     run_config_model: str | Model | None = None,+    workspace_scope: SandboxWorkspaceScope | None = None, ) -> Agent[TContext]:     manifest = session.state.manifest+    effective_workspace_scope = workspace_scope or SandboxWorkspaceScope()      available_capability_types = {capability.type for capability in capabilities}     for capability in capabilities:@@ -98,6 +121,7 @@ def prepare_sandbox_agent(             additional_instructions=agent.instructions,             capabilities=capabilities,             manifest=manifest,+            workspace_scope=effective_workspace_scope,         ),         model_settings=replace(             model_settings,@@ -155,7 +179,10 @@ def build_sandbox_instructions(     | None,     capabilities: Sequence[Capability],     manifest: Manifest,+    workspace_scope: SandboxWorkspaceScope | None = None, ) -> Callable[[RunContextWrapper[TContext], Agent[TContext]], Awaitable[str | None]]:+    effective_workspace_scope = workspace_scope or SandboxWorkspaceScope()+     async def _instructions(         run_context: RunContextWrapper[TContext],         current_agent: Agent[TContext],@@ -201,7 +228,7 @@ def build_sandbox_instructions(         if remote_mount_policy := build_remote_mount_policy_instructions(manifest):             parts.append(_instruction_section("Sandbox remote mount policy", remote_mount_policy)) -        parts.append(_filesystem_instructions(manifest))+        parts.append(_filesystem_instructions(manifest, effective_workspace_scope))          return "\n\n".join(parts) if parts else None src/agents/sandbox/workspace_paths.pyindex 4cdc49fef..2a5b28a60 100644@@ -3,6 +3,7 @@ from __future__ import annotations import os import posixpath import re+from dataclasses import dataclass from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath from typing import Literal, cast @@ -66,6 +67,135 @@ def sandbox_path_str(path: str | PurePath) -> str:     return coerce_posix_path(path).as_posix()  +def normalize_sandbox_cwd(cwd: str | PurePath) -> PurePosixPath:+    """Validate and normalize a run working directory relative to the workspace root."""++    if isinstance(cwd, PurePath):+        raw_cwd = cwd.as_posix()+    elif isinstance(cwd, str):+        if "\\" in cwd:+            raise ValueError("sandbox.cwd must use POSIX path separators")+        raw_cwd = cwd+    else:+        raise ValueError("sandbox.cwd must be a string or Path")++    if not raw_cwd.strip():+        raise ValueError("sandbox.cwd must be non-empty")+    if windows_absolute_path(cwd) is not None:+        raise ValueError("sandbox.cwd must be workspace-relative")++    posix_cwd = PurePosixPath(raw_cwd)+    if posix_cwd.is_absolute():+        raise ValueError("sandbox.cwd must be workspace-relative")+    if ".." in posix_cwd.parts:+        raise ValueError("sandbox.cwd must not contain parent segments")++    return PurePosixPath(posixpath.normpath(posix_cwd.as_posix()))+++def _is_absolute_sandbox_path(path: str | PurePath) -> bool:+    if windows_absolute_path(path) is not None:+        return True+    raw_path = path.as_posix() if isinstance(path, PurePath) else path+    return PurePosixPath(raw_path).is_absolute()+++@dataclass(frozen=True)+class SandboxWorkspaceScope:+    """Immutable model-facing relative-path base for one sandbox run.++    This scope changes only how relative paths are anchored. The owning sandbox session and its+    existing workspace policy remain responsible for access validation and filesystem operations.+    """++    cwd: PurePosixPath | None = None++    def __post_init__(self) -> None:+        if self.cwd is not None:+            object.__setattr__(self, "cwd", normalize_sandbox_cwd(self.cwd))++    @classmethod+    def from_cwd(cls, cwd: str | PurePath | None) -> SandboxWorkspaceScope:+        """Create a scope from an optional workspace-relative working directory."""++        return cls(cwd=normalize_sandbox_cwd(cwd) if cwd is not None else None)++    def anchor(self, path: str | PurePath) -> str | PurePath:+        """Anchor a relative sandbox path beneath this scope's working directory."""++        if self.cwd is None or _is_absolute_sandbox_path(path):+            return path+        raw_path = path.as_posix() if isinstance(path, PurePath) else path+        return self.cwd / PurePosixPath(raw_path)++    def model_path(self, workspace_relative_path: str | PurePath) -> PurePosixPath:+        """Render a workspace-root-relative path relative to the model-facing cwd."""++        relative_path = coerce_posix_path(workspace_relative_path)+        if relative_path.is_absolute():+            raise ValueError("workspace-relative display paths must not be absolute")+        if self.cwd is None:+            return PurePosixPath(posixpath.normpath(relative_path.as_posix()))+        return PurePosixPath(+            posixpath.relpath(+                posixpath.normpath(relative_path.as_posix()),+                start=self.cwd.as_posix(),+            )+        )++    def model_resource_path(+        self,+        *,+        workspace_root: str | PurePath,+        workspace_relative_path: str | PurePath,+    ) -> PurePosixPath:+        """Render a session-owned workspace resource for model-facing instructions.++        Without a run cwd, preserve the existing workspace-root-relative representation. With a+        run cwd, use an absolute sandbox path so the resource remains addressable after a shell+        command selects a nested workdir or changes directory.+        """++        if isinstance(workspace_relative_path, str) and "\\" in workspace_relative_path:+            raise ValueError("session resource paths must use POSIX path separators")+        if windows_absolute_path(workspace_relative_path) is not None:+            raise ValueError("session resource paths must be workspace-relative")++        relative_path = coerce_posix_path(workspace_relative_path)+        if relative_path.is_absolute() or ".." in relative_path.parts:+            raise ValueError("session resource paths must be workspace-relative")+        if relative_path.parts in [(), (".",)]:+            raise ValueError("session resource paths must be non-empty")++        normalized_path = PurePosixPath(posixpath.normpath(relative_path.as_posix()))+        if self.cwd is None:+            return normalized_path++        windows_root = windows_absolute_path(workspace_root)+        if windows_root is not None:+            root_path = PurePosixPath(windows_root.as_posix())+        else:+            if isinstance(workspace_root, str) and "\\" in workspace_root:+                raise ValueError("sandbox workspace root must be POSIX absolute")+            root_path = coerce_posix_path(workspace_root)+            if not root_path.is_absolute():+                raise ValueError("sandbox workspace root must be POSIX absolute")+        return PurePosixPath(posixpath.normpath((root_path / normalized_path).as_posix()))++    def display_path(+        self,+        *,+        original_path: str | PurePath,+        workspace_relative_path: str | PurePath,+    ) -> PurePosixPath:+        """Render a tool result path without changing existing absolute-input display behavior."""++        relative_path = coerce_posix_path(workspace_relative_path)+        if self.cwd is None or _is_absolute_sandbox_path(original_path):+            return PurePosixPath(posixpath.normpath(relative_path.as_posix()))+        return self.model_path(relative_path)++ def _native_path_from_windows_absolute(path: PureWindowsPath) -> Path | None:     native_path = Path(path)     return native_path if native_path.is_absolute() else Nonetests/sandbox/capabilities/test_apply_patch_tool.pyindex 5948cded2..db877dea7 100644@@ -3,11 +3,12 @@ from __future__ import annotations import asyncio import json from collections.abc import Awaitable-from pathlib import Path+from pathlib import Path, PureWindowsPath from typing import Any, cast  import pytest +import agents.sandbox.apply_patch as sandbox_apply_patch from agents import Agent, CustomTool, RunHooks from agents.editor import ApplyPatchOperation, ApplyPatchResult from agents.items import ToolApprovalItem, ToolCallOutputItem@@ -16,11 +17,14 @@ from agents.run import RunConfig from agents.run_context import RunContextWrapper from agents.run_internal.run_steps import ToolRunCustom from agents.run_internal.tool_actions import CustomToolAction+from agents.sandbox import SandboxWorkspaceScope from agents.sandbox.capabilities.tools import SandboxApplyPatchTool+from agents.sandbox.errors import ApplyPatchDecodeError, ApplyPatchFileNotFoundError from agents.sandbox.types import User from agents.testing import scripted_sandbox_session from tests.sandbox._apply_patch_test_session import (     ApplyPatchSession,+    ProviderNotFoundApplyPatchSession,     UserRecordingApplyPatchSession, ) from tests.utils.hitl import make_context_wrapper@@ -263,6 +267,207 @@ class TestSandboxApplyPatchTool:         assert delete_result.output == "Deleted notes.txt"         assert Path("/workspace/notes.txt") not in session.files +    @pytest.mark.asyncio+    async def test_editor_scopes_paths_and_move_outputs_to_run_cwd(self) -> None:+        session = ApplyPatchSession()+        tool = SandboxApplyPatchTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        create_result = await tool.editor.create_file(+            ApplyPatchOperation(+                type="create_file",+                path="notes.txt",+                diff="+hello\n",+            )+        )+        move_result = await tool.editor.update_file(+            ApplyPatchOperation(+                type="update_file",+                path="notes.txt",+                diff="@@\n-hello\n+hi\n",+                move_to="archive/notes.txt",+            )+        )++        assert create_result.output == "Created notes.txt"+        assert move_result.output == "Updated notes.txt\nMoved notes.txt to archive/notes.txt"+        assert Path("/workspace/tasks/a/notes.txt") not in session.files+        assert session.files[Path("/workspace/tasks/a/archive/notes.txt")] == b"hi"++    @pytest.mark.asyncio+    async def test_editor_keeps_absolute_path_behavior_with_workspace_scope(self) -> None:+        session = ApplyPatchSession()+        tool = SandboxApplyPatchTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        result = await tool.editor.create_file(+            ApplyPatchOperation(+                type="create_file",+                path="/workspace/root.txt",+                diff="+root\n",+            )+        )++        assert result.output == "Created root.txt"+        assert session.files[Path("/workspace/root.txt")] == b"root"++    @pytest.mark.asyncio+    async def test_editor_scoped_missing_error_uses_model_relative_path(self) -> None:+        session = ProviderNotFoundApplyPatchSession()+        tool = SandboxApplyPatchTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        with pytest.raises(ApplyPatchFileNotFoundError) as exc_info:+            await tool.editor.update_file(+                ApplyPatchOperation(+                    type="update_file",+                    path="missing.txt",+                    diff="@@\n-old\n+new\n",+                )+            )++        assert str(exc_info.value) == "apply_patch missing file: missing.txt"+        assert exc_info.value.context["path"] == "missing.txt"+        assert "/provider/private/root" not in str(exc_info.value)++    @pytest.mark.asyncio+    async def test_editor_scoped_decode_error_uses_posix_model_relative_path_on_windows(+        self, monkeypatch: pytest.MonkeyPatch+    ) -> None:+        monkeypatch.setattr(sandbox_apply_patch, "Path", PureWindowsPath)+        session = ApplyPatchSession()+        session.files[Path("/workspace/tasks/a/nested/binary.txt")] = b"\xff\xfe\xfd"+        tool = SandboxApplyPatchTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        with pytest.raises(ApplyPatchDecodeError) as exc_info:+            await tool.editor.update_file(+                ApplyPatchOperation(+                    type="update_file",+                    path="nested/binary.txt",+                    diff="@@\n+replacement\n",+                )+            )++        assert str(exc_info.value) == "apply_patch could not decode file: nested/binary.txt"+        assert exc_info.value.context["path"] == "nested/binary.txt"+        assert "/workspace/tasks/a" not in str(exc_info.value)++    @pytest.mark.asyncio+    async def test_editor_scoped_decode_error_keeps_posix_absolute_path_on_windows(+        self, monkeypatch: pytest.MonkeyPatch+    ) -> None:+        monkeypatch.setattr(sandbox_apply_patch, "Path", PureWindowsPath)+        session = ApplyPatchSession()+        session.files[Path("/workspace/root/nested/binary.txt")] = b"\xff\xfe\xfd"+        tool = SandboxApplyPatchTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        with pytest.raises(ApplyPatchDecodeError) as exc_info:+            await tool.editor.update_file(+                ApplyPatchOperation(+                    type="update_file",+                    path="/workspace/root/nested/binary.txt",+                    diff="@@\n+replacement\n",+                )+            )++        expected_path = "/workspace/root/nested/binary.txt"+        assert str(exc_info.value) == f"apply_patch could not decode file: {expected_path}"+        assert exc_info.value.context["path"] == expected_path++    @pytest.mark.asyncio+    async def test_scoped_tool_approval_receives_execution_canonical_paths(self) -> None:+        checked_operations: list[tuple[str, str | None]] = []++        async def needs_approval(+            _ctx: RunContextWrapper[Any], operation: ApplyPatchOperation, _call_id: str+        ) -> bool:+            checked_operations.append((operation.path, operation.move_to))+            return False++        session = ApplyPatchSession()+        session.files[Path("/workspace/tasks/a/notes.txt")] = b"old\n"+        tool = SandboxApplyPatchTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+            needs_approval=needs_approval,+        )++        result = await _execute_custom_tool_call(+            tool,+            context_wrapper=make_context_wrapper(),+            raw_input=(+                "*** Begin Patch\n"+                "*** Update File: notes.txt\n"+                "*** Move to: moved.txt\n"+                "@@\n"+                "-old\n"+                "+new\n"+                "*** End Patch\n"+            ),+        )++        assert checked_operations == [("tasks/a/notes.txt", "tasks/a/moved.txt")]+        assert result.output == "Updated notes.txt\nMoved notes.txt to moved.txt"+        assert session.files[Path("/workspace/tasks/a/moved.txt")] == b"new\n"++    @pytest.mark.asyncio+    async def test_scoped_custom_tool_keeps_absolute_path_at_workspace_root(self) -> None:+        session = ApplyPatchSession()+        tool = SandboxApplyPatchTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        result = await _execute_custom_tool_call(+            tool,+            context_wrapper=make_context_wrapper(),+            raw_input=(+                "*** Begin Patch\n*** Add File: /workspace/root.txt\n+root\n*** End Patch\n"+            ),+        )++        assert result.output == "Created root.txt"+        assert session.files[Path("/workspace/root.txt")] == b"root"+        assert Path("/workspace/tasks/a/root.txt") not in session.files++    @pytest.mark.asyncio+    async def test_direct_session_apply_patch_remains_workspace_root_relative(self) -> None:+        session = ApplyPatchSession()+        tool = SandboxApplyPatchTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        await session.apply_patch(+            ApplyPatchOperation(+                type="create_file",+                path="direct.txt",+                diff="+root\n",+            )+        )+        await tool.editor.create_file(+            ApplyPatchOperation(+                type="create_file",+                path="tool.txt",+                diff="+scoped\n",+            )+        )++        assert session.files[Path("/workspace/direct.txt")] == b"root"+        assert session.files[Path("/workspace/tasks/a/tool.txt")] == b"scoped"+     @pytest.mark.asyncio     async def test_editor_runs_file_operations_as_bound_user(self) -> None:         session = UserRecordingApplyPatchSession()tests/sandbox/capabilities/test_filesystem_capability.pyindex 6bd3b5580..081667cde 100644@@ -7,7 +7,7 @@ from typing import Any, cast import pytest  from agents.editor import ApplyPatchOperation-from agents.sandbox import Manifest+from agents.sandbox import Manifest, SandboxWorkspaceScope from agents.sandbox.capabilities import Filesystem, FilesystemToolSet from agents.sandbox.capabilities.tools import SandboxApplyPatchTool, ViewImageTool from agents.sandbox.sandboxes.unix_local import (@@ -87,6 +87,7 @@ class TestFilesystemCapability:             nonlocal replacement_view_image             replacement_view_image = ViewImageTool(                 session=toolset.view_image.session,+                workspace_scope=toolset.workspace_scope,                 needs_approval=True,             )             toolset.view_image = replacement_view_image@@ -102,6 +103,23 @@ class TestFilesystemCapability:         assert view_image_tool.needs_approval is True         assert isinstance(tools[1], SandboxApplyPatchTool) +    def test_tools_and_configurator_receive_bound_workspace_scope(self, tmp_path: Path) -> None:+        scope = SandboxWorkspaceScope.from_cwd("tasks/a")+        configured_scopes: list[SandboxWorkspaceScope] = []++        def configure_tools(toolset: FilesystemToolSet) -> None:+            configured_scopes.append(toolset.workspace_scope)++        capability = Filesystem(configure_tools=configure_tools)+        capability.bind(_make_session(tmp_path))+        capability.bind_workspace_scope(scope)++        tools = capability.tools()++        assert configured_scopes == [scope]+        assert cast(ViewImageTool, tools[0]).workspace_scope is scope+        assert cast(SandboxApplyPatchTool, tools[1]).workspace_scope is scope+     def test_tools_passes_bound_run_as_to_file_tools(self, tmp_path: Path) -> None:         run_as = User(name="sandbox-user")         capability = Filesystem()tests/sandbox/capabilities/test_shell_capability.pyindex 38ff54c2a..45375561a 100644@@ -5,7 +5,7 @@ from typing import Any, cast  import pytest -from agents.sandbox import Manifest, SandboxPathGrant+from agents.sandbox import Manifest, SandboxPathGrant, SandboxWorkspaceScope from agents.sandbox.capabilities import Shell, ShellToolSet from agents.sandbox.capabilities.tools import (     ExecCommandArgs,@@ -196,6 +196,23 @@ class TestShellCapability:         assert exec_command_tool is replacement_exec_command         assert exec_command_tool.needs_approval is True +    def test_configure_tools_receives_workspace_scope(self) -> None:+        observed_scope: SandboxWorkspaceScope | None = None++        def configure_tools(toolset: ShellToolSet) -> None:+            nonlocal observed_scope+            observed_scope = toolset.workspace_scope++        capability = Shell(configure_tools=configure_tools)+        capability.bind(_shell_session())+        scope = SandboxWorkspaceScope.from_cwd("tasks/a")+        capability.bind_workspace_scope(scope)++        tool = cast(ExecCommandTool, capability.tools()[0])++        assert observed_scope is scope+        assert tool.workspace_scope is scope+     @pytest.mark.asyncio     async def test_instructions_match_sandbox_shell_guidance(self) -> None:         capability = Shell()@@ -263,6 +280,7 @@ class TestShellCapability:         )         capability.bind(session)         capability.bind_run_as(User(name="sandbox-user"))+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/a"))         tool = cast(FunctionTool, capability.tools()[0])          await tool.on_invoke_tool(@@ -270,6 +288,7 @@ class TestShellCapability:             ExecCommandArgs(cmd="pwd").model_dump_json(),         ) +        assert session.calls[0].args == ("cd /workspace/tasks/a && pwd",)         assert session.calls[0].kwargs["user"] == User(name="sandbox-user")         session.assert_complete() @@ -346,6 +365,57 @@ class TestShellCapability:             "stderr: cd /workspace/src/project && pwd"         ) +    @pytest.mark.asyncio+    @pytest.mark.parametrize("workdir", [None, "", "   "])+    async def test_exec_command_tool_defaults_to_workspace_scope_cwd(+        self,+        workdir: str | None,+    ) -> None:+        capability = Shell()+        session = _shell_session()+        capability.bind(session)+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/a"))+        tool = cast(FunctionTool, capability.tools()[0])++        await tool.on_invoke_tool(+            cast(ToolContext[object], None),+            ExecCommandArgs(cmd="pwd", workdir=workdir).model_dump_json(),+        )++        assert session.calls[0].args == ("cd /workspace/tasks/a && pwd",)++    @pytest.mark.asyncio+    async def test_exec_command_tool_resolves_relative_workdir_from_workspace_scope(self) -> None:+        capability = Shell()+        session = _shell_session()+        capability.bind(session)+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/a"))+        tool = cast(FunctionTool, capability.tools()[0])++        await tool.on_invoke_tool(+            cast(ToolContext[object], None),+            ExecCommandArgs(cmd="pwd", workdir="src/project").model_dump_json(),+        )++        assert session.calls[0].args == ("cd /workspace/tasks/a/src/project && pwd",)++    @pytest.mark.asyncio+    async def test_exec_command_tool_normalizes_raw_backslashes_before_workspace_scope(+        self,+    ) -> None:+        capability = Shell()+        session = _shell_session()+        capability.bind(session)+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/a"))+        tool = cast(FunctionTool, capability.tools()[0])++        await tool.on_invoke_tool(+            cast(ToolContext[object], None),+            ExecCommandArgs(cmd="pwd", workdir=r"src\project").model_dump_json(),+        )++        assert session.calls[0].args == ("cd /workspace/tasks/a/src/project && pwd",)+     @pytest.mark.asyncio     async def test_exec_command_tool_allows_split_path_grant_workdir(         self,@@ -365,6 +435,7 @@ class TestShellCapability:             )         )         capability.bind(session)+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/a"))         tool = cast(FunctionTool, capability.tools()[0])         _patch_shell_tool_clock(             monkeypatch,@@ -415,6 +486,7 @@ class TestShellCapability:             ]         )         capability.bind(session)+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/a"))         tool = cast(FunctionTool, capability.tools()[0])         _patch_shell_tool_clock(             monkeypatch,@@ -428,6 +500,7 @@ class TestShellCapability:             ExecCommandArgs(cmd="pwd", yield_time_ms=0, tty=True).model_dump_json(),         ) +        assert session.calls[0].args == ("cd /workspace/tasks/a && pwd",)         assert session.calls[0].kwargs["yield_time_s"] == 0.0         assert (             output == "Chunk ID: abcdef\n"@@ -509,7 +582,10 @@ class TestShellCapability:                 },             ]         )-        tool = ExecCommandTool(session=session)+        tool = ExecCommandTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )         _patch_shell_tool_clock(             monkeypatch,             chunk_id="44444444444444444444444444444444",@@ -526,6 +602,8 @@ class TestShellCapability:         assert "Process exited with code 0" in output         assert "Process running with session ID" not in output         assert "fallback ok" in output+        assert session.calls[0].args == ("cd /workspace/tasks/a && pwd",)+        assert session.calls[1].args == ("cd /workspace/tasks/a && pwd",)      @pytest.mark.asyncio     async def test_exec_command_tool_does_not_fall_back_for_tty_sessions(self) -> None:tests/sandbox/capabilities/test_skills_capability.pyindex cb2961efe..417e32cff 100644@@ -2,13 +2,19 @@ from __future__ import annotations  import io import uuid-from pathlib import Path+from pathlib import Path, PurePath, PureWindowsPath from typing import cast  import pytest  from agents.sandbox import Manifest, SandboxPathGrant-from agents.sandbox.capabilities import LocalDirLazySkillSource, Skill, Skills+from agents.sandbox.capabilities import (+    LazySkillSource,+    LocalDirLazySkillSource,+    Skill,+    SkillMetadata,+    Skills,+) from agents.sandbox.entries import Dir, File, LocalDir from agents.sandbox.errors import (     SkillsConfigError,@@ -20,7 +26,11 @@ from agents.sandbox.session.base_sandbox_session import BaseSandboxSession from agents.sandbox.session.sandbox_session import SandboxSession from agents.sandbox.snapshot import NoopSnapshot from agents.sandbox.types import ExecResult, FileMode, Group, Permissions, User-from agents.sandbox.workspace_paths import coerce_posix_path, sandbox_path_str+from agents.sandbox.workspace_paths import (+    SandboxWorkspaceScope,+    coerce_posix_path,+    sandbox_path_str,+) from agents.testing import scripted_sandbox_session from agents.tool import FunctionTool from agents.tool_context import ToolContext@@ -47,6 +57,39 @@ def _user_name(user: object) -> str | None:     return str(user)  +class _StaticResultLazySkillSource(LazySkillSource):+    result: dict[str, str]+    metadata_path: PurePath | None = None++    def list_skill_metadata(+        self,+        *,+        skills_path: str,+        source_grants: tuple[SandboxPathGrant, ...] = (),+    ) -> list[SkillMetadata]:+        _ = (skills_path, source_grants)+        if self.metadata_path is None:+            return []+        return [+            SkillMetadata(+                name="dynamic-skill",+                description="dynamic description",+                path=self.metadata_path,+            )+        ]++    async def load_skill(+        self,+        *,+        skill_name: str,+        session: BaseSandboxSession,+        skills_path: str,+        user: str | User | None = None,+    ) -> dict[str, str]:+        _ = (skill_name, session, skills_path, user)+        return dict(self.result)++ class _SkillsSession(BaseSandboxSession):     def __init__(self, manifest: Manifest) -> None:         self.state = TestSessionState(@@ -392,6 +435,7 @@ class TestSkillsInstructions:         assert "### How to use skills" in instructions         assert "- a-skill: a description (file: .agents/a-skill)" in instructions         assert "- z-skill: z description (file: .agents/z-skill)" in instructions+        assert "### Run-scoped skill paths" not in instructions         assert instructions.index(             "- a-skill: a description (file: .agents/a-skill)"         ) < instructions.index("- z-skill: z description (file: .agents/z-skill)")@@ -408,6 +452,20 @@ class TestSkillsInstructions:         assert instructions is not None         assert "- my-skill: desc (file: .sandbox/skills/my-skill)" in instructions +    @pytest.mark.asyncio+    async def test_instructions_render_session_owned_paths_as_absolute_with_run_cwd(self) -> None:+        capability = Skills(+            skills=[Skill(name="my-skill", description="desc", content="literal")],+        )+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/task-a"))++        instructions = await capability.instructions(Manifest(root="/workspace"))++        assert instructions is not None+        assert "- my-skill: desc (file: /workspace/.agents/my-skill)" in instructions+        assert "Treat each listed path as the skill root" in instructions+        assert "write task inputs, outputs, caches, and temporary files" in instructions+     @pytest.mark.asyncio     async def test_instructions_return_none_when_metadata_is_empty(self) -> None:         capability = Skills(from_=Dir())@@ -457,12 +515,14 @@ class TestSkillsInstructions:         session = _SkillsSession(manifest)         await session.apply_manifest()         capability.bind(session)+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/task-a"))          instructions = await capability.instructions(session.state.manifest)          assert instructions is not None         assert (-            "- discovered-skill: loaded from runtime frontmatter (file: .agents/dynamic-skill)"+            "- discovered-skill: loaded from runtime frontmatter "+            f"(file: {workspace_root.as_posix()}/.agents/dynamic-skill)"         ) in instructions      @pytest.mark.asyncio@@ -557,6 +617,35 @@ class TestSkillsInstructions:         loaded_skill = workspace_root / ".agents" / "dynamic-skill" / "SKILL.md"         assert loaded_skill.read_text(encoding="utf-8") == "# dynamic skill\n" +    @pytest.mark.asyncio+    async def test_lazy_load_reports_absolute_path_without_relocating_skill(+        self, tmp_path: Path+    ) -> None:+        workspace_root = tmp_path / "workspace"+        workspace_root.mkdir()+        src_root = tmp_path / "skills"+        skill_dir = src_root / "dynamic-skill"+        skill_dir.mkdir(parents=True)+        (skill_dir / "SKILL.md").write_text("# dynamic skill\n", encoding="utf-8")+        capability = Skills(+            lazy_from=LocalDirLazySkillSource(source=LocalDir(src=src_root)),+        )+        session = _SkillsSession(+            capability.process_manifest(_source_granted_manifest(workspace_root, source=src_root))+        )+        capability.bind(session)+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/task-a"))++        output = await capability.load_skill("dynamic-skill")++        assert output == {+            "status": "loaded",+            "skill_name": "dynamic-skill",+            "path": f"{workspace_root.as_posix()}/.agents/dynamic-skill",+        }+        assert (workspace_root / ".agents" / "dynamic-skill" / "SKILL.md").is_file()+        assert not (workspace_root / "tasks" / "task-a" / ".agents").exists()+     @pytest.mark.asyncio     async def test_lazy_local_dir_load_skill_applies_source_metadata(self, tmp_path: Path) -> None:         workspace_root = tmp_path / "workspace"@@ -622,6 +711,75 @@ class TestSkillsInstructions:   class TestSkillsLazyLoading:+    @pytest.mark.asyncio+    async def test_custom_lazy_result_is_unchanged_without_run_cwd(self) -> None:+        expected = {"status": "loaded", "detail": "opaque"}+        capability = Skills(lazy_from=_StaticResultLazySkillSource(result=expected))+        capability.bind(scripted_sandbox_session(manifest=Manifest(root="/workspace")))++        output = await capability.load_skill("dynamic-skill")++        assert output == expected++    @pytest.mark.asyncio+    @pytest.mark.parametrize(+        ("result", "reason"),+        [+            ({"status": "loaded"}, "missing"),+            ({"status": "loaded", "path": "../escape"}, "invalid"),+            ({"status": "loaded", "path": r".agents\dynamic-skill"}, "invalid"),+        ],+    )+    async def test_custom_lazy_result_requires_valid_path_with_run_cwd(+        self,+        result: dict[str, str],+        reason: str,+    ) -> None:+        capability = Skills(lazy_from=_StaticResultLazySkillSource(result=result))+        capability.bind(scripted_sandbox_session(manifest=Manifest(root="/workspace")))+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/task-a"))++        with pytest.raises(SkillsConfigError) as exc_info:+            await capability.load_skill("dynamic-skill")++        assert exc_info.value.message == (+            "skill path must be non-empty and workspace-relative when sandbox.cwd is configured"+        )+        assert exc_info.value.context["skill_name"] == "dynamic-skill"+        assert exc_info.value.context["field"] == "path"+        assert exc_info.value.context["reason"] == reason++    @pytest.mark.asyncio+    @pytest.mark.parametrize(+        "metadata_path",+        [Path("../outside"), PureWindowsPath("../outside")],+    )+    async def test_custom_lazy_metadata_reports_invalid_scoped_path_as_config_error(+        self,+        metadata_path: PurePath,+    ) -> None:+        capability = Skills(+            lazy_from=_StaticResultLazySkillSource(+                result={"status": "loaded", "path": ".agents/dynamic-skill"},+                metadata_path=metadata_path,+            )+        )+        capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/task-a"))++        with pytest.raises(SkillsConfigError) as exc_info:+            await capability.instructions(Manifest(root="/workspace"))++        assert exc_info.value.message == (+            "skill path must be non-empty and workspace-relative when sandbox.cwd is configured"+        )+        assert exc_info.value.context == {+            "skill_name": "dynamic-skill",+            "field": "path",+            "path": "../outside",+            "reason": "invalid",+        }+        assert isinstance(exc_info.value.cause, ValueError)+     def test_tools_returns_empty_without_lazy_source(self) -> None:         capability = Skills(skills=[Skill(name="my-skill", description="desc", content="literal")]) tests/sandbox/capabilities/test_view_image_tool.pyindex 64ecd403e..5fc93f6ba 100644@@ -7,8 +7,8 @@ from typing import cast  import pytest -from agents.sandbox import Manifest, SandboxPathGrant-from agents.sandbox.capabilities.tools import ViewImageTool+from agents.sandbox import Manifest, SandboxPathGrant, SandboxWorkspaceScope+from agents.sandbox.capabilities.tools import ViewImageArgs, ViewImageTool from agents.sandbox.errors import InvalidManifestPathError, WorkspaceReadNotFoundError from agents.sandbox.types import User from agents.testing import scripted_sandbox_session@@ -81,6 +81,109 @@ class TestViewImageTool:          assert session.calls == () +    @pytest.mark.asyncio+    async def test_view_image_resolves_relative_path_from_workspace_scope(self) -> None:+        session = scripted_sandbox_session(+            [{"method": "read", "result": io.BytesIO(_PNG_BYTES)}],+            manifest=Manifest(root="/workspace"),+        )+        tool = ViewImageTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        output = await tool.on_invoke_tool(+            cast(ToolContext[object], None),+            '{"path":"images/dot.png"}',+        )++        assert isinstance(output, ToolOutputImage)+        assert session.calls[0].args == (Path("/workspace/tasks/a/images/dot.png"),)+        session.assert_complete()++    @pytest.mark.asyncio+    async def test_view_image_normalizes_raw_backslashes_before_workspace_scope(self) -> None:+        session = scripted_sandbox_session(+            [{"method": "read", "result": io.BytesIO(_PNG_BYTES)}],+            manifest=Manifest(root="/workspace"),+        )+        tool = ViewImageTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        output = await tool.run(ViewImageArgs(path=r"images\dot.png"))++        assert isinstance(output, ToolOutputImage)+        assert session.calls[0].args == (Path("/workspace/tasks/a/images/dot.png"),)+        session.assert_complete()++    @pytest.mark.asyncio+    async def test_view_image_keeps_absolute_path_behavior_with_workspace_scope(self) -> None:+        session = scripted_sandbox_session(+            [{"method": "read", "result": io.BytesIO(b"hello\n")}],+            manifest=Manifest(root="/workspace"),+        )+        tool = ViewImageTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        output = await tool.on_invoke_tool(+            cast(ToolContext[object], None),+            '{"path":"/workspace/notes.txt"}',+        )++        assert output == "image path `notes.txt` is not a supported image file"+        assert session.calls[0].args == (Path("/workspace/notes.txt"),)+        session.assert_complete()++    @pytest.mark.asyncio+    async def test_view_image_reports_raw_posix_absolute_path_after_normalization(self) -> None:+        session = scripted_sandbox_session(+            [{"method": "read", "result": io.BytesIO(b"hello\n")}],+            manifest=Manifest(root="/workspace"),+        )+        tool = ViewImageTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        output = await tool.run(ViewImageArgs(path=r"\workspace\root.txt"))++        assert output == "image path `root.txt` is not a supported image file"+        assert session.calls[0].args == (Path("/workspace/root.txt"),)+        session.assert_complete()++    @pytest.mark.asyncio+    async def test_view_image_scoped_error_uses_model_relative_path(self) -> None:+        provider_root = Path("/provider/private/root")+        session = scripted_sandbox_session(+            [+                {+                    "method": "read",+                    "error": WorkspaceReadNotFoundError(+                        path=provider_root / "tasks/a/images/missing.png"+                    ),+                }+            ],+            manifest=Manifest(root="/workspace"),+        )+        tool = ViewImageTool(+            session=session,+            workspace_scope=SandboxWorkspaceScope.from_cwd("tasks/a"),+        )++        output = await tool.on_invoke_tool(+            cast(ToolContext[object], None),+            '{"path":"images/missing.png"}',+        )++        assert output == "image path `images/missing.png` was not found"+        assert str(provider_root) not in output+        assert session.calls[0].args == (Path("/workspace/tasks/a/images/missing.png"),)+        session.assert_complete()+     @pytest.mark.asyncio     async def test_view_image_reads_as_bound_user(self) -> None:         session = scripted_sandbox_session([{"method": "read", "result": io.BytesIO(_PNG_BYTES)}])tests/sandbox/test_compatibility_guards.pyindex 0e3a2bcea..ab68c3f8f 100644@@ -115,6 +115,7 @@ def test_core_sandbox_public_export_surface_is_stable() -> None:             "SandboxAgent",             "SandboxArchiveLimits",             "SandboxPathGrant",+            "SandboxWorkspaceScope",             "SandboxConcurrencyLimits",             "SandboxError",             "SandboxRunConfig",@@ -368,6 +369,7 @@ def test_sandbox_dataclass_constructor_field_order_is_stable() -> None:         "snapshot",         "concurrency_limits",         "archive_limits",+        "cwd",     )  tests/sandbox/test_memory.pyindex 75ad62112..bfd7d3663 100644@@ -75,6 +75,7 @@ from agents.sandbox.memory.storage import ( ) from agents.sandbox.runtime import _stream_memory_input_override from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient+from agents.sandbox.workspace_paths import SandboxWorkspaceScope from agents.testing import ScriptedModel from tests.test_responses import get_final_output_message, get_text_message from tests.utils.hitl import make_shell_call@@ -989,6 +990,99 @@ async def test_memory_capability_live_update_instructions() -> None:         await client.delete(session)  +@pytest.mark.asyncio+async def test_memory_capability_renders_session_owned_paths_as_absolute_with_run_cwd() -> None:+    client = UnixLocalSandboxClient()+    session = await client.create(manifest=Manifest())+    capability = Memory(generate=None)++    try:+        async with session:+            await session.mkdir("memories", parents=True)+            await session.write(+                Path("memories/memory_summary.md"),+                io.BytesIO(b"summary entry"),+            )+            capability.bind(session)+            capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/task-a"))++            instructions = await capability.instructions(session.state.manifest)++            assert instructions is not None+            workspace_root = session.state.manifest.root+            assert (+                f"{workspace_root}/memories/memory_summary.md "+                "(already provided below; do NOT open again)" in instructions+            )+            assert f"{workspace_root}/memories/MEMORY.md" in instructions+            assert "summary entry" in instructions+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+@pytest.mark.parametrize("memories_dir", [r"team\memory", "team//memory"])+async def test_memory_capability_preserves_layout_spelling_without_run_cwd(+    memories_dir: str,+) -> None:+    client = UnixLocalSandboxClient()+    session = await client.create(manifest=Manifest())+    capability = Memory(+        layout=MemoryLayoutConfig(memories_dir=memories_dir),+        generate=None,+    )++    try:+        async with session:+            await session.mkdir(Path(memories_dir), parents=True)+            await session.write(+                Path(memories_dir) / "memory_summary.md",+                io.BytesIO(b"summary entry"),+            )+            capability.bind(session)++            instructions = await capability.instructions(session.state.manifest)++            assert instructions is not None+            assert f"{memories_dir}/memory_summary.md" in instructions+            assert f"{memories_dir}/MEMORY.md" in instructions+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+async def test_memory_capability_uses_typed_layout_path_with_run_cwd() -> None:+    memories_dir = r"team\memory"+    client = UnixLocalSandboxClient()+    session = await client.create(manifest=Manifest())+    capability = Memory(+        layout=MemoryLayoutConfig(memories_dir=memories_dir),+        generate=None,+    )++    try:+        async with session:+            memory_dir_path = Path(memories_dir)+            await session.mkdir(memory_dir_path, parents=True)+            await session.write(+                memory_dir_path / "memory_summary.md",+                io.BytesIO(b"summary entry"),+            )+            capability.bind(session)+            capability.bind_workspace_scope(SandboxWorkspaceScope.from_cwd("tasks/task-a"))++            instructions = await capability.instructions(session.state.manifest)++            assert instructions is not None+            workspace_root = session.state.manifest.root+            assert (+                f"{workspace_root}/{memory_dir_path.as_posix()}/memory_summary.md" in instructions+            )+            assert f"{workspace_root}/{memory_dir_path.as_posix()}/MEMORY.md" in instructions+    finally:+        await client.delete(session)++ @pytest.mark.asyncio async def test_sandbox_memory_writes_rollouts_and_memory_files() -> None:     client = UnixLocalSandboxClient()tests/sandbox/test_run_cwd.pynew file mode 100644index 000000000..234d7019f@@ -0,0 +1,360 @@+from __future__ import annotations++import asyncio+import base64+import io+import shlex+import sys+from collections.abc import Awaitable, Callable+from pathlib import Path+from typing import TYPE_CHECKING, Any++import pytest+from openai.types.responses import ResponseCustomToolCall++from agents import RunConfig, Runner, ToolOutputImage+from agents.items import ToolCallOutputItem+from agents.run_state import RunState+from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig+from agents.sandbox.capabilities import (+    Filesystem,+    FilesystemToolSet,+    Shell,+    ShellToolSet,+    Skill,+    Skills,+)+from agents.sandbox.entries import File+from agents.sandbox.errors import WorkspaceReadNotFoundError+from agents.sandbox.session.base_sandbox_session import BaseSandboxSession+from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call++if TYPE_CHECKING or sys.platform != "win32":+    from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient++_PNG_BYTES = base64.b64decode(+    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a84QAAAAASUVORK5CYII="+)+_SVG_BYTES = b'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>'+_IMAGE_BY_TASK = {+    "task-a": ("image/png", _PNG_BYTES),+    "task-b": ("image/svg+xml", _SVG_BYTES),+}+++async def _read_bytes(session: BaseSandboxSession, path: str) -> bytes:+    file_obj = await session.read(Path(path))+    try:+        payload = file_obj.read()+    finally:+        file_obj.close()+    return payload if isinstance(payload, bytes) else payload.encode("utf-8")+++@pytest.mark.asyncio+@pytest.mark.skipif(sys.platform == "win32", reason="Unix local sandbox is unavailable on Windows")+async def test_concurrent_runs_scope_relative_paths_with_shared_live_session() -> None:+    client = UnixLocalSandboxClient()+    session = await client.create(manifest=Manifest())+    both_runs_ready = asyncio.Event()+    ready_count = 0+    ready_lock = asyncio.Lock()++    def first_step(task_name: str) -> Callable[[Any], Awaitable[list[Any]]]:+        async def respond(_call: Any) -> list[Any]:+            nonlocal ready_count+            async with ready_lock:+                ready_count += 1+                if ready_count == 2:+                    both_runs_ready.set()+            await asyncio.wait_for(both_runs_ready.wait(), timeout=5)+            return [+                function_call(+                    "exec_command",+                    {"cmd": "cp seed.png plot.png", "login": False},+                    call_id=f"{task_name}_shell",+                )+            ]++        return respond++    def build_model(task_name: str) -> ScriptedModel:+        return ScriptedModel(+            [+                ModelStep.respond(first_step(task_name)),+                [+                    function_call(+                        "view_image",+                        {"path": "plot.png"},+                        call_id=f"{task_name}_image",+                    )+                ],+                [+                    ResponseCustomToolCall(+                        id=f"{task_name}_patch_item",+                        type="custom_tool_call",+                        name="apply_patch",+                        call_id=f"{task_name}_patch",+                        input=(+                            "*** Begin Patch\n"+                            "*** Add File: notes.md\n"+                            f"+{task_name}\n"+                            "*** End Patch\n"+                        ),+                    )+                ],+                [assistant_message("done", item_id=f"{task_name}_message")],+            ]+        )++    models = {task_name: build_model(task_name) for task_name in ("task-a", "task-b")}+    agents = {+        task_name: SandboxAgent(+            name=task_name,+            model=models[task_name],+            capabilities=[Shell(), Filesystem()],+        )+        for task_name in models+    }++    try:+        async with session:+            for task_name in models:+                task_dir = f"tasks/{task_name}"+                await session.mkdir(task_dir, parents=True)+                await session.write(+                    Path(task_dir) / "seed.png",+                    io.BytesIO(_IMAGE_BY_TASK[task_name][1]),+                )++            results = await asyncio.gather(+                *(+                    Runner.run(+                        agents[task_name],+                        "Create the requested task-local artifacts.",+                        run_config=RunConfig(+                            sandbox=SandboxRunConfig(+                                session=session,+                                cwd=f"tasks/{task_name}",+                            )+                        ),+                    )+                    for task_name in models+                )+            )++            for task_name, result in zip(models, results, strict=True):+                assert result.final_output == "done"+                outputs = {+                    item.call_id: item.output+                    for item in result.new_items+                    if isinstance(item, ToolCallOutputItem)+                }+                image_output = outputs[f"{task_name}_image"]+                assert isinstance(image_output, ToolOutputImage)+                mime_type, image_bytes = _IMAGE_BY_TASK[task_name]+                assert image_output.image_url == (+                    f"data:{mime_type};base64,{base64.b64encode(image_bytes).decode('ascii')}"+                )+                assert outputs[f"{task_name}_patch"] == "Created notes.md"+                assert await _read_bytes(session, f"tasks/{task_name}/plot.png") == image_bytes+                assert (+                    await _read_bytes(session, f"tasks/{task_name}/notes.md") == task_name.encode()+                )+                models[task_name].assert_complete()++            for root_relative_path in ("plot.png", "notes.md"):+                with pytest.raises(WorkspaceReadNotFoundError):+                    await session.read(Path(root_relative_path))+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+@pytest.mark.skipif(sys.platform == "win32", reason="Unix local sandbox is unavailable on Windows")+async def test_python_skill_uses_absolute_root_from_nested_workdir() -> None:+    skill_script = (+        b"from pathlib import Path\n"+        b"skill_root = Path(__file__).parent.parent\n"+        b"suffix = (skill_root / 'assets' / 'suffix.txt').read_text(encoding='utf-8')\n"+        b"source = Path('input.txt').read_text(encoding='utf-8')\n"+        b"Path('output.txt').write_text(source + suffix, encoding='utf-8')\n"+    )+    skills = Skills(+        skills=[+            Skill(+                name="python-proof",+                description="Proves shared Python skills keep task files local.",+                content="# Python proof\n",+                scripts={"prove.py": File(content=skill_script)},+                assets={"suffix.txt": File(content=b"-from-shared-skill")},+            )+        ]+    )+    client = UnixLocalSandboxClient()+    session = await client.create(manifest=skills.process_manifest(Manifest()))++    try:+        async with session:+            await session.mkdir("tasks/task-a/nested", parents=True)+            await session.write(+                Path("tasks/task-a/nested/input.txt"),+                io.BytesIO(b"task-a"),+            )+            workspace_root = session.state.manifest.root+            skill_root = f"{workspace_root}/.agents/python-proof"+            script_path = f"{skill_root}/scripts/prove.py"+            model = ScriptedModel(+                [+                    [+                        function_call(+                            "exec_command",+                            {+                                "cmd": (+                                    f"{shlex.quote(sys.executable)} {shlex.quote(script_path)}"+                                ),+                                "workdir": "nested",+                                "login": False,+                            },+                            call_id="python_skill",+                        )+                    ],+                    [assistant_message("done", item_id="python_skill_message")],+                ]+            )+            agent = SandboxAgent(+                name="python-skill-task",+                model=model,+                capabilities=[Shell(), skills],+            )++            result = await Runner.run(+                agent,+                "Use the available Python skill.",+                run_config=RunConfig(sandbox=SandboxRunConfig(session=session, cwd="tasks/task-a")),+            )++            assert result.final_output == "done"+            assert await _read_bytes(session, "tasks/task-a/nested/output.txt") == (+                b"task-a-from-shared-skill"+            )+            assert (+                await _read_bytes(session, ".agents/python-proof/scripts/prove.py") == skill_script+            )+            instructions = model.calls[0].system_instructions+            assert instructions is not None+            assert f"(file: {skill_root})" in instructions+            assert "Treat each listed path as the skill root" in instructions+            assert "Files outside the working directory may be visible to or shared" in instructions+            model.assert_complete()+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+@pytest.mark.skipif(sys.platform == "win32", reason="Unix local sandbox is unavailable on Windows")+async def test_resumed_run_rebinds_cwd_to_pending_sandbox_tool() -> None:+    client = UnixLocalSandboxClient()+    session = await client.create(manifest=Manifest())++    def require_exec_approval(toolset: ShellToolSet) -> None:+        toolset.exec_command.needs_approval = True++    model = ScriptedModel(+        [+            [+                function_call(+                    "exec_command",+                    {"cmd": "printf resumed > marker.txt", "login": False},+                    call_id="resumed_shell",+                )+            ],+            [assistant_message("done", item_id="resumed_message")],+        ]+    )+    agent = SandboxAgent(+        name="resumed-task",+        model=model,+        capabilities=[Shell(configure_tools=require_exec_approval)],+    )+    run_config = RunConfig(sandbox=SandboxRunConfig(session=session, cwd="tasks/resumed-task"))++    try:+        async with session:+            await session.mkdir("tasks/resumed-task", parents=True)++            first = await Runner.run(agent, "Create the marker.", run_config=run_config)+            assert len(first.interruptions) == 1+            state = first.to_state()+            state.approve(first.interruptions[0])++            resumed = await Runner.run(agent, state, run_config=run_config)++            assert resumed.final_output == "done"+            assert await _read_bytes(session, "tasks/resumed-task/marker.txt") == b"resumed"+            with pytest.raises(WorkspaceReadNotFoundError):+                await session.read(Path("marker.txt"))+            model.assert_complete()+    finally:+        await client.delete(session)+++@pytest.mark.asyncio+@pytest.mark.parametrize("serialize_state", [False, True], ids=["in-memory", "json"])+@pytest.mark.skipif(sys.platform == "win32", reason="Unix local sandbox is unavailable on Windows")+async def test_resumed_apply_patch_uses_current_run_cwd(serialize_state: bool) -> None:+    client = UnixLocalSandboxClient()+    session = await client.create(manifest=Manifest())++    def require_apply_patch_approval(toolset: FilesystemToolSet) -> None:+        toolset.apply_patch.needs_approval = True++    model = ScriptedModel(+        [+            [+                ResponseCustomToolCall(+                    id="patch_item",+                    type="custom_tool_call",+                    name="apply_patch",+                    call_id="patch_call",+                    input=("*** Begin Patch\n*** Add File: marker.txt\n+resumed\n*** End Patch\n"),+                )+            ],+            [assistant_message("done", item_id="resumed_patch_message")],+        ]+    )+    agent = SandboxAgent(+        name="resumed-patch-task",+        model=model,+        capabilities=[Filesystem(configure_tools=require_apply_patch_approval)],+    )++    try:+        async with session:+            await session.mkdir("tasks/a", parents=True)+            await session.mkdir("tasks/b", parents=True)++            first = await Runner.run(+                agent,+                "Create the marker.",+                run_config=RunConfig(sandbox=SandboxRunConfig(session=session, cwd="tasks/a")),+            )+            assert len(first.interruptions) == 1+            state = first.to_state()+            if serialize_state:+                state = await RunState.from_json(agent, state.to_json())+            state.approve(state.get_interruptions()[0])++            resumed = await Runner.run(+                agent,+                state,+                run_config=RunConfig(sandbox=SandboxRunConfig(session=session, cwd="tasks/b")),+            )++            assert resumed.final_output == "done"+            assert await _read_bytes(session, "tasks/b/marker.txt") == b"resumed"+            with pytest.raises(WorkspaceReadNotFoundError):+                await session.read(Path("tasks/a/marker.txt"))+            model.assert_complete()+    finally:+        await client.delete(session)tests/sandbox/test_runtime.pyindex fcef40cb0..ef37d6fb0 100644@@ -12,7 +12,7 @@ import tarfile import tempfile import uuid from collections.abc import Sequence-from pathlib import Path+from pathlib import Path, PurePosixPath, PureWindowsPath from typing import Any, ClassVar, Literal, TypedDict, cast  import pytest@@ -55,6 +55,11 @@ from agents.sandbox.capabilities import (     Shell,     StaticCompactionPolicy, )+from agents.sandbox.capabilities.tools import (+    ExecCommandTool,+    SandboxApplyPatchTool,+    ViewImageTool,+) from agents.sandbox.entries import (     BaseEntry,     DockerVolumeMountStrategy,@@ -209,6 +214,34 @@ class _FakeSession(BaseSandboxSession):         await super()._aclose_dependencies()  +class _CwdProbeSession(_FakeSession):+    def __init__(self, manifest: Manifest, *, accessible: bool = True) -> None:+        super().__init__(manifest)+        self.accessible = accessible+        self.cwd_probe_calls: list[tuple[tuple[str, ...], bool | list[str], User | str | None]] = []++    async def exec(+        self,+        *command: str | Path,+        timeout: float | None = None,+        shell: bool | list[str] = True,+        user: str | User | None = None,+    ) -> ExecResult:+        _ = timeout+        self.cwd_probe_calls.append((tuple(str(part) for part in command), shell, user))+        return ExecResult(+            stdout=b"",+            stderr=b"" if self.accessible else b"not accessible",+            exit_code=0 if self.accessible else 1,+        )+++class _WindowsPathCwdProbeSession(_CwdProbeSession):+    def normalize_path(self, path: Path | str, *, for_write: bool = False) -> Path:+        _ = (path, for_write)+        return cast(Path, PureWindowsPath("/workspace/tasks/a"))++ class _FailingStopSession(_FakeSession):     async def stop(self) -> None:         await super().stop()@@ -5863,6 +5896,192 @@ async def test_prepare_agent_rechecks_session_liveness_before_reusing_cached_age     assert session.start_calls == 2  +@pytest.mark.asyncio+async def test_prepare_agent_revalidates_cwd_after_restarting_cached_session() -> None:+    session = _CwdProbeSession(Manifest())+    client = _FakeClient(session)+    agent = SandboxAgent(+        name="sandbox",+        model=ScriptedModel(steps=[[get_final_output_message("done")]]),+        run_as="sandbox-user",+    )+    runtime = SandboxRuntime(+        starting_agent=agent,+        run_config=RunConfig(+            sandbox=SandboxRunConfig(+                client=client,+                options={"image": "sandbox"},+                cwd="tasks/a",+            )+        ),+        run_state=None,+    )+    context_wrapper = RunContextWrapper(context=None)++    await runtime.prepare_agent(+        current_agent=agent,+        current_input="hello",+        context_wrapper=context_wrapper,+        is_resumed_state=False,+    )+    session._running = False+    session.accessible = False++    with pytest.raises(+        UserError,+        match=r"Sandbox working directory `tasks/a` does not exist or is not accessible",+    ):+        await runtime.prepare_agent(+            current_agent=agent,+            current_input="hello again",+            context_wrapper=context_wrapper,+            is_resumed_state=False,+        )++    assert session.start_calls == 2+    assert session.cwd_probe_calls == [+        (("test", "-d", "/workspace/tasks/a"), False, User(name="sandbox-user")),+        (("test", "-x", "/workspace/tasks/a"), False, User(name="sandbox-user")),+        (("test", "-d", "/workspace/tasks/a"), False, User(name="sandbox-user")),+    ]+++@pytest.mark.asyncio+async def test_prepare_agent_revalidates_cwd_when_cached_agent_run_as_changes() -> None:+    session = _CwdProbeSession(Manifest())+    client = _FakeClient(session)+    agent = SandboxAgent(+        name="sandbox",+        model=ScriptedModel(steps=[[get_final_output_message("done")]]),+        run_as="first-user",+    )+    runtime = SandboxRuntime(+        starting_agent=agent,+        run_config=RunConfig(+            sandbox=SandboxRunConfig(+                client=client,+                options={"image": "sandbox"},+                cwd="tasks/a",+            )+        ),+        run_state=None,+    )+    context_wrapper = RunContextWrapper(context=None)++    await runtime.prepare_agent(+        current_agent=agent,+        current_input="hello",+        context_wrapper=context_wrapper,+        is_resumed_state=False,+    )+    agent.run_as = "second-user"+    session.accessible = False+    session.cwd_probe_calls.clear()++    with pytest.raises(+        UserError,+        match=r"Sandbox working directory `tasks/a` does not exist or is not accessible",+    ):+        await runtime.prepare_agent(+            current_agent=agent,+            current_input="hello again",+            context_wrapper=context_wrapper,+            is_resumed_state=False,+        )++    assert session.cwd_probe_calls == [+        (+            ("test", "-d", "/workspace/tasks/a"),+            False,+            User(name="second-user"),+        )+    ]+++@pytest.mark.asyncio+async def test_prepare_agent_rematerializes_cached_tools_when_run_as_changes() -> None:+    session = _CwdProbeSession(Manifest())+    client = _FakeClient(session)+    run_as = User(name="first-user")+    agent = SandboxAgent(+        name="sandbox",+        model=ScriptedModel(steps=[[get_final_output_message("done")]]),+        capabilities=[Shell(), Filesystem()],+        run_as=run_as,+    )+    runtime = SandboxRuntime(+        starting_agent=agent,+        run_config=RunConfig(+            sandbox=SandboxRunConfig(+                client=client,+                options={"image": "sandbox"},+                cwd="tasks/a",+            )+        ),+        run_state=None,+    )+    context_wrapper = RunContextWrapper(context=None)++    first = await runtime.prepare_agent(+        current_agent=agent,+        current_input="first",+        context_wrapper=context_wrapper,+        is_resumed_state=False,+    )+    first_agent = cast(SandboxAgent[Any], first.bindings.execution_agent)+    first_capabilities = list(first_agent.capabilities)+    first_shell = next(tool for tool in first_agent.tools if isinstance(tool, ExecCommandTool))+    first_view = next(tool for tool in first_agent.tools if isinstance(tool, ViewImageTool))+    first_patch = next(+        tool for tool in first_agent.tools if isinstance(tool, SandboxApplyPatchTool)+    )+    assert first_shell.user == User(name="first-user")+    assert first_view.user == User(name="first-user")+    assert first_patch.editor.user == User(name="first-user")++    run_as.name = "second-user"+    second = await runtime.prepare_agent(+        current_agent=agent,+        current_input="second",+        context_wrapper=context_wrapper,+        is_resumed_state=False,+    )+    second_agent = cast(SandboxAgent[Any], second.bindings.execution_agent)++    assert second_agent is not first_agent+    assert all(+        second_capability is first_capability+        for second_capability, first_capability in zip(+            second_agent.capabilities,+            first_capabilities,+            strict=True,+        )+    )+    second_shell = next(tool for tool in second_agent.tools if isinstance(tool, ExecCommandTool))+    second_view = next(tool for tool in second_agent.tools if isinstance(tool, ViewImageTool))+    second_patch = next(+        tool for tool in second_agent.tools if isinstance(tool, SandboxApplyPatchTool)+    )+    assert second_shell.user == User(name="second-user")+    assert second_view.user == User(name="second-user")+    assert second_patch.editor.user == User(name="second-user")++    third = await runtime.prepare_agent(+        current_agent=agent,+        current_input="third",+        context_wrapper=context_wrapper,+        is_resumed_state=False,+    )++    assert third.bindings.execution_agent is second_agent+    assert session.cwd_probe_calls[-4:] == [+        (("test", "-d", "/workspace/tasks/a"), False, User(name="second-user")),+        (("test", "-x", "/workspace/tasks/a"), False, User(name="second-user")),+        (("test", "-d", "/workspace/tasks/a"), False, User(name="second-user")),+        (("test", "-x", "/workspace/tasks/a"), False, User(name="second-user")),+    ]++ @pytest.mark.asyncio async def test_prepare_agent_binds_run_as_to_cloned_capabilities() -> None:     session = _FakeSession(Manifest())@@ -5894,6 +6113,108 @@ async def test_prepare_agent_binds_run_as_to_cloned_capabilities() -> None:     assert prepared_capability.run_as == User(name="sandbox-user")  +@pytest.mark.asyncio+async def test_prepare_agent_binds_and_validates_run_workspace_scope() -> None:+    session = _CwdProbeSession(Manifest())+    client = _FakeClient(session)+    capability = _RecordingCapability()+    agent = SandboxAgent(+        name="sandbox",+        model=ScriptedModel(steps=[[get_final_output_message("done")]]),+        capabilities=[capability],+        run_as="sandbox-user",+    )+    runtime = SandboxRuntime(+        starting_agent=agent,+        run_config=RunConfig(+            sandbox=SandboxRunConfig(+                client=client,+                options={"image": "sandbox"},+                cwd="tasks/a",+            )+        ),+        run_state=None,+    )++    prepared = await runtime.prepare_agent(+        current_agent=agent,+        current_input="hello",+        context_wrapper=RunContextWrapper(context=None),+        is_resumed_state=False,+    )++    execution_agent = cast(SandboxAgent[Any], prepared.bindings.execution_agent)+    prepared_capability = cast(_RecordingCapability, execution_agent.capabilities[0])+    assert capability.workspace_scope.cwd is None+    assert prepared_capability.workspace_scope.cwd == PurePosixPath("tasks/a")+    assert session.cwd_probe_calls == [+        (("test", "-d", "/workspace/tasks/a"), False, User(name="sandbox-user")),+        (("test", "-x", "/workspace/tasks/a"), False, User(name="sandbox-user")),+    ]+++@pytest.mark.asyncio+async def test_prepare_agent_serializes_cwd_probe_with_posix_sandbox_semantics() -> None:+    session = _WindowsPathCwdProbeSession(Manifest())+    client = _FakeClient(session)+    agent = SandboxAgent(name="sandbox", model=ScriptedModel())+    runtime = SandboxRuntime(+        starting_agent=agent,+        run_config=RunConfig(+            sandbox=SandboxRunConfig(+                client=client,+                options={"image": "sandbox"},+                cwd="tasks/a",+            )+        ),+        run_state=None,+    )+    await runtime.prepare_agent(+        current_agent=agent,+        current_input="hello",+        context_wrapper=RunContextWrapper(context=None),+        is_resumed_state=False,+    )++    assert session.cwd_probe_calls == [+        (("test", "-d", "/workspace/tasks/a"), False, None),+        (("test", "-x", "/workspace/tasks/a"), False, None),+    ]+++@pytest.mark.asyncio+async def test_prepare_agent_rejects_inaccessible_run_workspace_scope() -> None:+    session = _CwdProbeSession(Manifest(), accessible=False)+    client = _FakeClient(session)+    agent = SandboxAgent(name="sandbox", model=ScriptedModel())+    runtime = SandboxRuntime(+        starting_agent=agent,+        run_config=RunConfig(+            sandbox=SandboxRunConfig(+                client=client,+                options={"image": "sandbox"},+                cwd="tasks/missing",+            )+        ),+        run_state=None,+    )++    with pytest.raises(+        UserError,+        match=r"Sandbox working directory `tasks/missing` does not exist or is not accessible",+    ):+        await runtime.prepare_agent(+            current_agent=agent,+            current_input="hello",+            context_wrapper=RunContextWrapper(context=None),+            is_resumed_state=False,+        )++    assert session.cwd_probe_calls == [+        (("test", "-d", "/workspace/tasks/missing"), False, None),+    ]++ @pytest.mark.asyncio async def test_prepare_agent_processes_context_with_bound_cached_capabilities() -> None:     session = _FakeSession(Manifest())tests/sandbox/test_runtime_agent_preparation.pyindex d5054a8b7..2a78885e9 100644@@ -10,7 +10,11 @@ import pytest from agents import UserError from agents.models.default_models import get_default_model from agents.run_context import RunContextWrapper-from agents.sandbox import MemoryReadConfig, runtime_agent_preparation as sandbox_prep+from agents.sandbox import (+    MemoryReadConfig,+    SandboxWorkspaceScope,+    runtime_agent_preparation as sandbox_prep,+) from agents.sandbox.capabilities import Capability, Compaction, Memory from agents.sandbox.entries import BaseEntry, File from agents.sandbox.manifest import Manifest@@ -248,6 +252,30 @@ def test_filesystem_instructions_tell_model_to_ls_when_manifest_tree_is_truncate     ) in result  +def test_filesystem_instructions_describe_run_working_directory() -> None:+    manifest = Manifest(root="/workspace", entries={"tasks/a": File(content=b"")})++    result = sandbox_prep._filesystem_instructions(+        manifest,+        SandboxWorkspaceScope.from_cwd("tasks/a"),+    )++    assert "For this run, the working directory is `/workspace/tasks/a`." in result+    assert (+        "Relative paths passed to the built-in `exec_command`, `view_image`, and `apply_patch` "+        "tools resolve from this directory."+    ) in result+    assert "Other sandbox tools follow their own path contract." in result+    assert "The session workspace root remains `/workspace`." in result+    assert (+        "The working directory changes path resolution; it does not isolate this run from the "+        "rest of the session workspace."+    ) in result+    assert (+        "Files outside the working directory may be visible to or shared with other runs." in result+    )++ def test_prepare_sandbox_agent_validates_required_capabilities() -> None:     manifest = Manifest(root="/workspace") tests/sandbox/test_workspace_paths.pyindex e5d5cde09..ba76d7974 100644@@ -9,11 +9,12 @@ from typing import Any, cast import pytest from pydantic import ValidationError -from agents.sandbox import Manifest, SandboxPathGrant+from agents.sandbox import Manifest, SandboxPathGrant, SandboxWorkspaceScope from agents.sandbox.errors import InvalidManifestPathError, WorkspaceArchiveWriteError from agents.sandbox.workspace_paths import (     WorkspacePathPolicy,     coerce_posix_path,+    normalize_sandbox_cwd,     posix_path_as_path,     sandbox_path_grant_host_path, )@@ -35,6 +36,141 @@ def _policy(root: Path | str = "/workspace") -> WorkspacePathPolicy:     return WorkspacePathPolicy(root=root)  +def test_sandbox_workspace_scope_anchors_relative_paths() -> None:+    scope = SandboxWorkspaceScope.from_cwd("tasks/a")++    assert scope.anchor("plot.png") == PurePosixPath("tasks/a/plot.png")+    assert scope.anchor(PureWindowsPath("reports/plot.png")) == PurePosixPath(+        "tasks/a/reports/plot.png"+    )+    assert scope.anchor("/workspace/plot.png") == "/workspace/plot.png"+    assert scope.anchor(PureWindowsPath("C:/plot.png")) == PureWindowsPath("C:/plot.png")+++def test_sandbox_workspace_scope_preserves_raw_tool_backslashes() -> None:+    scope = SandboxWorkspaceScope.from_cwd("tasks/a")++    anchored = scope.anchor(r"reports\plot.png")++    assert isinstance(anchored, PurePosixPath)+    assert anchored.as_posix() == r"tasks/a/reports\plot.png"+++def test_sandbox_workspace_scope_renders_model_paths() -> None:+    scope = SandboxWorkspaceScope.from_cwd("tasks/a")++    assert scope.model_path("tasks/a/plot.png") == PurePosixPath("plot.png")+    assert scope.model_path("shared/skill/SKILL.md") == PurePosixPath("../../shared/skill/SKILL.md")+    assert scope.display_path(+        original_path="../shared.txt",+        workspace_relative_path="tasks/shared.txt",+    ) == PurePosixPath("../shared.txt")+    assert scope.display_path(+        original_path="/workspace/shared.txt",+        workspace_relative_path="shared.txt",+    ) == PurePosixPath("shared.txt")+++def test_sandbox_workspace_scope_renders_session_resources_as_absolute_with_cwd() -> None:+    scope = SandboxWorkspaceScope.from_cwd("tasks/a")++    assert scope.model_resource_path(+        workspace_root="/workspace",+        workspace_relative_path=".agents/my-skill",+    ) == PurePosixPath("/workspace/.agents/my-skill")+    assert scope.model_resource_path(+        workspace_root="/workspace",+        workspace_relative_path=PureWindowsPath(r".agents\my-skill"),+    ) == PurePosixPath("/workspace/.agents/my-skill")+    assert scope.model_resource_path(+        workspace_root=PureWindowsPath(r"C:\workspace"),+        workspace_relative_path=".agents/my-skill",+    ) == PurePosixPath("C:/workspace/.agents/my-skill")+    assert scope.model_resource_path(+        workspace_root=r"C:\workspace",+        workspace_relative_path=".agents/my-skill",+    ) == PurePosixPath("C:/workspace/.agents/my-skill")+++def test_sandbox_workspace_scope_preserves_root_relative_resource_paths_without_cwd() -> None:+    scope = SandboxWorkspaceScope()++    assert scope.model_resource_path(+        workspace_root="/workspace",+        workspace_relative_path=".agents/my-skill",+    ) == PurePosixPath(".agents/my-skill")+++@pytest.mark.parametrize(+    ("path", "message"),+    [+        ("/workspace/.agents/my-skill", "must be workspace-relative"),+        ("../my-skill", "must be workspace-relative"),+        ("C:/skills/my-skill", "must be workspace-relative"),+        (PureWindowsPath("C:/skills/my-skill"), "must be workspace-relative"),+        (r".agents\my-skill", "must use POSIX path separators"),+        ("", "must be non-empty"),+    ],+)+def test_sandbox_workspace_scope_rejects_invalid_session_resource_paths(+    path: str | PurePath,+    message: str,+) -> None:+    scope = SandboxWorkspaceScope.from_cwd("tasks/a")++    with pytest.raises(ValueError, match=message):+        scope.model_resource_path(+            workspace_root="/workspace",+            workspace_relative_path=path,+        )+++@pytest.mark.parametrize(+    "root",+    [r"\workspace", "workspace"],+)+def test_sandbox_workspace_scope_rejects_non_posix_absolute_resource_roots(+    root: str | PurePath,+) -> None:+    scope = SandboxWorkspaceScope.from_cwd("tasks/a")++    with pytest.raises(ValueError, match="sandbox workspace root must be POSIX absolute"):+        scope.model_resource_path(+            workspace_root=root,+            workspace_relative_path=".agents/my-skill",+        )+++def test_sandbox_workspace_scope_none_preserves_root_relative_paths() -> None:+    scope = SandboxWorkspaceScope()++    assert scope.anchor("plot.png") == "plot.png"+    assert scope.model_path("reports/plot.png") == PurePosixPath("reports/plot.png")+++def test_sandbox_workspace_scope_constructor_validates_cwd() -> None:+    with pytest.raises(ValueError, match="sandbox.cwd must not contain parent segments"):+        SandboxWorkspaceScope(cwd=PurePosixPath("tasks/../a"))+++@pytest.mark.parametrize(+    ("cwd", "message"),+    [+        ("", "sandbox.cwd must be non-empty"),+        ("/workspace/tasks/a", "sandbox.cwd must be workspace-relative"),+        ("tasks/../a", "sandbox.cwd must not contain parent segments"),+        (r"tasks\a", "sandbox.cwd must use POSIX path separators"),+        (PureWindowsPath("C:/tasks/a"), "sandbox.cwd must be workspace-relative"),+    ],+)+def test_normalize_sandbox_cwd_rejects_invalid_values(+    cwd: str | PurePath,+    message: str,+) -> None:+    with pytest.raises(ValueError, match=message):+        normalize_sandbox_cwd(cwd)++ def test_workspace_path_policy_rejects_relative_root() -> None:     with pytest.raises(ValueError, match="sandbox workspace root must be absolute"):         WorkspacePathPolicy(root="workspace")tests/test_run_config.pyindex 1e61f4e8d..8c88046af 100644@@ -1,5 +1,6 @@ from __future__ import annotations +from pathlib import PureWindowsPath from typing import Any, cast  import pytest@@ -47,6 +48,7 @@ def test_run_config_normalizes_first_party_dictionary_settings() -> None:             "manifest": {"root": "/workspace"},             "snapshot": {"type": "noop"},             "concurrency_limits": {"manifest_entries": 3},+            "cwd": "tasks/a",         },     ) @@ -63,6 +65,28 @@ def test_run_config_normalizes_first_party_dictionary_settings() -> None:     assert isinstance(config.sandbox.snapshot, NoopSnapshotSpec)     assert isinstance(config.sandbox.concurrency_limits, SandboxConcurrencyLimits)     assert config.sandbox.concurrency_limits.manifest_entries == 3+    assert config.sandbox.cwd == "tasks/a"+++def test_sandbox_run_config_normalizes_typed_cwd() -> None:+    config = SandboxRunConfig(cwd=PureWindowsPath("tasks/a"))++    assert config.cwd == "tasks/a"+++@pytest.mark.parametrize(+    ("cwd", "message"),+    [+        ("", "sandbox.cwd must be non-empty"),+        ("/workspace/tasks/a", "sandbox.cwd must be workspace-relative"),+        ("tasks/../a", "sandbox.cwd must not contain parent segments"),+        (r"tasks\a", "sandbox.cwd must use POSIX path separators"),+        (PureWindowsPath("C:/tasks/a"), "sandbox.cwd must be workspace-relative"),+    ],+)+def test_sandbox_run_config_rejects_invalid_cwd(cwd: object, message: str) -> None:+    with pytest.raises(ValueError, match=message):+        SandboxRunConfig(cwd=cast(Any, cwd))   def test_run_config_preserves_typed_configuration_instances() -> None:tests/test_tool_approval_call_id_reuse.pyindex 6cff1d344..3f9f0671c 100644@@ -1103,6 +1103,207 @@ async def test_non_approval_custom_tool_identical_siblings_execute_once() -> Non     assert executed == ["safe"]  +@pytest.mark.asyncio+async def test_approved_custom_tool_resume_rebinds_to_current_tool() -> None:+    executed: list[str] = []++    async def invoke_original(_context: Any, value: str) -> str:+        executed.append(f"original:{value}")+        return value++    async def invoke_replacement(_context: Any, value: str) -> str:+        executed.append(f"replacement:{value}")+        return value++    original = CustomTool(+        name="raw_editor",+        description="Edit raw text.",+        on_invoke_tool=invoke_original,+        format={"type": "text"},+        needs_approval=True,+    )+    replacement = CustomTool(+        name="raw_editor",+        description="Edit raw text.",+        on_invoke_tool=invoke_replacement,+        format={"type": "text"},+        needs_approval=True,+    )+    call = ResponseCustomToolCall(+        type="custom_tool_call",+        name="raw_editor",+        call_id="call_0",+        input="safe",+    )+    model = ScriptedModel(steps=[[call], [get_text_message("done")]])+    agent = Agent(name="agent", model=model, tools=[original])++    first = await Runner.run(agent, "edit text")+    state = first.to_state()+    state.approve(state.get_interruptions()[0])+    agent.tools = [replacement]++    resumed = await Runner.run(agent, state)++    assert resumed.final_output == "done"+    assert executed == ["replacement:safe"]+++@pytest.mark.asyncio+async def test_approved_custom_tool_resume_fails_when_current_tool_is_missing() -> None:+    executed: list[str] = []++    async def invoke(_context: Any, value: str) -> str:+        executed.append(value)+        return value++    tool = CustomTool(+        name="raw_editor",+        description="Edit raw text.",+        on_invoke_tool=invoke,+        format={"type": "text"},+        needs_approval=True,+    )+    call = ResponseCustomToolCall(+        type="custom_tool_call",+        name="raw_editor",+        call_id="call_0",+        input="safe",+    )+    model = ScriptedModel(steps=[[call]])+    agent = Agent(name="agent", model=model, tools=[tool])++    first = await Runner.run(agent, "edit text")+    state = first.to_state()+    state.approve(state.get_interruptions()[0])+    agent.tools = []++    with pytest.raises(ModelBehaviorError, match="Tool raw_editor not found"):+        await Runner.run(agent, state)++    assert executed == []+++@pytest.mark.asyncio+async def test_approved_apply_patch_custom_resume_uses_public_tool() -> None:+    class RecordingEditor:+        def __init__(self) -> None:+            self.paths: list[str] = []++        def update_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:+            self.paths.append(operation.path)+            return ApplyPatchResult(status="completed", output="updated")++    editor = RecordingEditor()+    tool = ApplyPatchTool(editor=cast(Any, editor), needs_approval=True)+    call = ResponseCustomToolCall(+        type="custom_tool_call",+        name="apply_patch",+        call_id="patch_0",+        input=json.dumps(+            {+                "type": "update_file",+                "path": "safe.txt",+                "diff": "-old\n+new\n",+            }+        ),+    )+    model = ScriptedModel(steps=[[call], [get_text_message("done")]])+    agent = Agent(name="agent", model=model, tools=[tool])++    first = await Runner.run(agent, "update the file")+    state = first.to_state()+    state.approve(state.get_interruptions()[0])++    resumed = await Runner.run(agent, state)++    assert resumed.final_output == "done"+    assert editor.paths == ["safe.txt"]+++@pytest.mark.asyncio+async def test_pending_custom_tool_resume_survives_missing_current_tool() -> None:+    async def invoke(_context: Any, value: str) -> str:+        raise AssertionError(f"pending custom tool must not execute: {value}")++    tool = CustomTool(+        name="raw_editor",+        description="Edit raw text.",+        on_invoke_tool=invoke,+        format={"type": "text"},+        needs_approval=True,+    )+    call = ResponseCustomToolCall(+        type="custom_tool_call",+        name="raw_editor",+        call_id="call_0",+        input="safe",+    )+    agent = Agent(+        name="agent",+        model=ScriptedModel(steps=[[call]]),+        tools=[tool],+    )++    first = await Runner.run(agent, "edit")+    state = first.to_state()+    agent.tools = []++    resumed = await Runner.run(agent, state)++    assert len(resumed.interruptions) == 1+++@pytest.mark.asyncio+@pytest.mark.parametrize("serialize_state", [False, True], ids=["in-memory", "json"])+async def test_rejected_custom_tool_resume_emits_output_when_current_tool_is_missing(+    serialize_state: bool,+) -> None:+    executed: list[str] = []++    async def invoke(_context: Any, value: str) -> str:+        executed.append(value)+        return value++    tool = CustomTool(+        name="raw_editor",+        description="Edit raw text.",+        on_invoke_tool=invoke,+        format={"type": "text"},+        needs_approval=True,+    )+    call = ResponseCustomToolCall(+        type="custom_tool_call",+        name="raw_editor",+        call_id="call_0",+        input="safe",+    )+    model = ScriptedModel(steps=[[call], [get_text_message("done")]])+    agent = Agent(name="agent", model=model, tools=[tool])++    first = await Runner.run(agent, "edit text")+    state = first.to_state()+    state.reject(state.get_interruptions()[0])+    agent.tools = []+    if serialize_state:+        state = await RunState.from_json(agent, state.to_json())++    resumed = await Runner.run(agent, state)++    assert resumed.final_output == "done"+    assert executed == []+    model_input = model.calls[-1].input+    assert isinstance(model_input, list)+    rejection_outputs = [+        item+        for item in model_input+        if isinstance(item, dict)+        and item.get("type") == "custom_tool_call_output"+        and item.get("call_id") == "call_0"+    ]+    assert len(rejection_outputs) == 1++ @pytest.mark.asyncio @pytest.mark.parametrize("mode", ["non_streamed", "streamed"]) async def test_changed_same_id_siblings_fail_before_approval_callback(