Skip to content

Docker sandbox

DockerSandboxClient

Bases: BaseSandboxClient[DockerSandboxClientOptions]

Source code in src/agents/sandbox/sandboxes/docker.py
class DockerSandboxClient(BaseSandboxClient[DockerSandboxClientOptions]):
    backend_id = "docker"
    docker_client: DockerSDKClient
    _instrumentation: Instrumentation

    def __init__(
        self,
        docker_client: DockerSDKClient,
        *,
        instrumentation: Instrumentation | None = None,
        dependencies: Dependencies | None = None,
    ) -> None:
        super().__init__()
        self.docker_client = docker_client
        self._instrumentation = instrumentation or Instrumentation()
        self._dependencies = dependencies

    async def create(
        self,
        *,
        snapshot: SnapshotSpec | SnapshotBase | None = None,
        manifest: Manifest | None = None,
        options: DockerSandboxClientOptions,
    ) -> SandboxSession:
        image = options.image
        session_id = uuid.uuid4()
        manifest = manifest or Manifest()

        container = await self._create_container(
            image,
            manifest=manifest,
            exposed_ports=options.exposed_ports,
            session_id=session_id,
        )
        container.start()

        container_id = container.id
        assert container_id is not None
        snapshot_id = str(session_id)
        snapshot_instance = resolve_snapshot(snapshot, snapshot_id)
        state = DockerSandboxSessionState(
            session_id=session_id,
            manifest=manifest,
            image=image,
            snapshot=snapshot_instance,
            container_id=container_id,
            exposed_ports=options.exposed_ports,
        )

        inner = DockerSandboxSession(
            docker_client=self.docker_client,
            container=container,
            state=state,
        )
        return self._wrap_session(inner, instrumentation=self._instrumentation)

    async def delete(self, session: SandboxSession) -> SandboxSession:
        inner = session._inner
        if not isinstance(inner, DockerSandboxSession):
            raise TypeError("DockerSandboxClient.delete expects a DockerSandboxSession")
        volume_names = _docker_volume_names_for_manifest(
            inner.state.manifest,
            session_id=inner.state.session_id,
        )
        try:
            container = self.docker_client.containers.get(inner.state.container_id)
        except docker.errors.NotFound:
            container = None
        else:
            # Ensure teardown happens before removal.
            try:
                await inner.shutdown()
            except Exception:
                pass
            try:
                container.remove()
            except docker.errors.NotFound:
                pass

        for volume_name in volume_names:
            try:
                volume = self.docker_client.volumes.get(volume_name)
            except docker.errors.NotFound:
                continue
            volume.remove()
        return session

    async def resume(
        self,
        state: SandboxSessionState,
    ) -> SandboxSession:
        if not isinstance(state, DockerSandboxSessionState):
            raise TypeError("DockerSandboxClient.resume expects a DockerSandboxSessionState")
        container = self.get_container(state.container_id)
        reused_existing_container = container is not None
        if container is None:
            container = await self._create_container(
                state.image,
                manifest=state.manifest,
                exposed_ports=state.exposed_ports,
                session_id=state.session_id,
            )
            container_id = container.id
            assert container_id is not None
            state.container_id = container_id
            state.workspace_root_ready = False

        # Use the existing container (or the one we just created).
        inner = DockerSandboxSession(
            container=container, docker_client=self.docker_client, state=state
        )
        inner._resume_workspace_probe_pending = True
        inner._set_start_state_preserved(reused_existing_container)
        return self._wrap_session(inner, instrumentation=self._instrumentation)

    def deserialize_session_state(self, payload: dict[str, object]) -> SandboxSessionState:
        return DockerSandboxSessionState.model_validate(payload)

    async def _create_container(
        self,
        image: str,
        *,
        manifest: Manifest | None = None,
        exposed_ports: tuple[int, ...] = (),
        session_id: uuid.UUID | None = None,
    ) -> Container:
        # create image if it does not exist
        if not self.image_exists(image):
            repo, tag = parse_repository_tag(image)
            self.docker_client.images.pull(repo, tag=tag or None, all_tags=False)

        assert self.image_exists(image)
        environment: dict[str, str] | None = None
        if manifest:
            environment = await manifest.environment.resolve()
        create_kwargs: dict[str, object] = {
            "entrypoint": ["tail"],
            "image": image,
            "detach": True,
            "command": ["-f", "/dev/null"],
            "environment": environment,
        }
        if manifest is not None:
            docker_mounts = _build_docker_volume_mounts(manifest, session_id=session_id)
            if docker_mounts:
                create_kwargs["mounts"] = docker_mounts
            if _manifest_requires_fuse(manifest):
                create_kwargs.update(
                    devices=["/dev/fuse"],
                    cap_add=["SYS_ADMIN"],
                    security_opt=["apparmor:unconfined"],
                )
            elif _manifest_requires_sys_admin(manifest):
                create_kwargs.update(
                    cap_add=["SYS_ADMIN"],
                    security_opt=["apparmor:unconfined"],
                )
        if exposed_ports:
            create_kwargs["ports"] = {
                _docker_port_key(port): ("127.0.0.1", None) for port in exposed_ports
            }
        return self.docker_client.containers.create(**create_kwargs)

    def image_exists(self, image: str) -> bool:
        try:
            self.docker_client.images.get(image)
            return True
        except docker.errors.ImageNotFound:
            return False

    def get_container(self, container_id: str) -> Container | None:
        try:
            return self.docker_client.containers.get(container_id)
        except docker.errors.NotFound:
            return None

serialize_session_state

serialize_session_state(
    state: SandboxSessionState,
) -> dict[str, object]

Serialize backend-specific sandbox state into a JSON-compatible payload.

Source code in src/agents/sandbox/session/sandbox_client.py
def serialize_session_state(self, state: SandboxSessionState) -> dict[str, object]:
    """Serialize backend-specific sandbox state into a JSON-compatible payload."""
    return state.model_dump(mode="json")

DockerSandboxClientOptions

Bases: BaseSandboxClientOptions

Source code in src/agents/sandbox/sandboxes/docker.py
class DockerSandboxClientOptions(BaseSandboxClientOptions):
    type: Literal["docker"] = "docker"
    image: str
    exposed_ports: tuple[int, ...] = ()

    def __init__(
        self,
        image: str,
        exposed_ports: tuple[int, ...] = (),
        *,
        type: Literal["docker"] = "docker",
    ) -> None:
        super().__init__(
            type=type,
            image=image,
            exposed_ports=exposed_ports,
        )

DockerSandboxSession

Bases: BaseSandboxSession

Source code in src/agents/sandbox/sandboxes/docker.py
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
class DockerSandboxSession(BaseSandboxSession):
    _docker_client: DockerSDKClient
    _container: Container
    _workspace_root_ready: bool
    _resume_workspace_probe_pending: bool
    _pty_lock: asyncio.Lock
    _pty_processes: dict[int, _DockerPtyProcessEntry]
    _reserved_pty_process_ids: set[int]

    state: DockerSandboxSessionState
    _ARCHIVE_STAGING_DIR: Path = Path("/tmp/sandbox-docker-archive")

    def __init__(
        self,
        *,
        docker_client: DockerSDKClient,
        container: Container,
        state: DockerSandboxSessionState,
    ) -> None:
        self._docker_client = docker_client
        self._container = container
        self.state = state
        self._workspace_root_ready = state.workspace_root_ready
        self._resume_workspace_probe_pending = False
        self._pty_lock = asyncio.Lock()
        self._pty_processes = {}
        self._reserved_pty_process_ids = set()

    @classmethod
    def from_state(
        cls,
        state: DockerSandboxSessionState,
        *,
        container: Container,
        docker_client: DockerSDKClient,
    ) -> "DockerSandboxSession":
        return cls(docker_client=docker_client, container=container, state=state)

    def supports_docker_volume_mounts(self) -> bool:
        """Docker attaches volume-driver mounts when creating the container."""

        return True

    def supports_pty(self) -> bool:
        return True

    @property
    def container_id(self) -> str:
        return self.state.container_id

    async def _resolve_exposed_port(self, port: int) -> ExposedPortEndpoint:
        try:
            self._container.reload()
        except docker.errors.APIError as e:
            raise ExposedPortUnavailableError(
                port=port,
                exposed_ports=self.state.exposed_ports,
                reason="backend_unavailable",
                context={"backend": "docker", "detail": "container_reload_failed"},
                cause=e,
            ) from e

        attrs = getattr(self._container, "attrs", {}) or {}
        ports = attrs.get("NetworkSettings", {}).get("Ports", {})
        port_key = _docker_port_key(port)
        bindings = ports.get(port_key)
        if not isinstance(bindings, list) or not bindings:
            raise ExposedPortUnavailableError(
                port=port,
                exposed_ports=self.state.exposed_ports,
                reason="backend_unavailable",
                context={"backend": "docker", "detail": "port_not_published", "port_key": port_key},
            )

        binding = bindings[0]
        if not isinstance(binding, dict):
            raise ExposedPortUnavailableError(
                port=port,
                exposed_ports=self.state.exposed_ports,
                reason="backend_unavailable",
                context={
                    "backend": "docker",
                    "detail": "invalid_port_binding",
                    "port_key": port_key,
                },
            )

        host_ip = binding.get("HostIp")
        host_port = binding.get("HostPort")
        if not isinstance(host_ip, str) or not host_ip:
            host_ip = "127.0.0.1"
        if not isinstance(host_port, str) or not host_port.isdigit():
            raise ExposedPortUnavailableError(
                port=port,
                exposed_ports=self.state.exposed_ports,
                reason="backend_unavailable",
                context={"backend": "docker", "detail": "invalid_host_port", "port_key": port_key},
            )

        return ExposedPortEndpoint(host=host_ip, port=int(host_port), tls=False)

    def _archive_stage_path(self, *, name_hint: str) -> Path:
        # Unique name avoids clashes across concurrent reads/writes.
        return self._ARCHIVE_STAGING_DIR / f"{uuid.uuid4().hex}_{name_hint}"

    def _runtime_helpers(self) -> tuple[RuntimeHelperScript, ...]:
        return (RESOLVE_WORKSPACE_PATH_HELPER,)

    def _current_runtime_helper_cache_key(self) -> object | None:
        return self.state.container_id

    async def _normalize_path_for_io(self, path: Path | str) -> Path:
        return await self._normalize_path_for_remote_io(path)

    @staticmethod
    def _path_has_nested_skip(path: Path, *, skip_rel_paths: set[Path]) -> bool:
        return any(path in skip_path.parents for skip_path in skip_rel_paths)

    async def _copy_workspace_tree_pruned(
        self,
        *,
        src_dir: Path,
        dst_dir: Path,
        rel_dir: Path,
        skip_rel_paths: set[Path],
    ) -> None:
        for entry in await self.ls(src_dir):
            src_child = Path(entry.path)
            rel_child = rel_dir / src_child.name
            if rel_child in skip_rel_paths:
                continue

            dst_child = dst_dir / src_child.name
            if entry.is_dir() and self._path_has_nested_skip(
                rel_child,
                skip_rel_paths=skip_rel_paths,
            ):
                await self._exec_checked(
                    "mkdir",
                    "-p",
                    str(dst_child),
                    error_cls=WorkspaceArchiveReadError,
                    error_path=src_child,
                )
                await self._copy_workspace_tree_pruned(
                    src_dir=src_child,
                    dst_dir=dst_child,
                    rel_dir=rel_child,
                    skip_rel_paths=skip_rel_paths,
                )
                continue

            await self._exec_checked(
                "cp",
                "-R",
                "--",
                str(src_child),
                str(dst_child),
                error_cls=WorkspaceArchiveReadError,
                error_path=src_child,
            )

    async def _stage_workspace_copy(
        self,
        *,
        skip_rel_paths: set[Path],
    ) -> tuple[Path, Path]:
        root = Path(self.state.manifest.root)
        root_name = root.name or "workspace"
        staging_parent = self._archive_stage_path(name_hint="workspace")
        staging_workspace = staging_parent / root_name
        skip_workspace_root = any(
            mount_path == root
            for _mount, mount_path in self.state.manifest.ephemeral_mount_targets()
        )

        await self._exec_checked(
            "mkdir",
            "-p",
            str(staging_parent),
            error_cls=WorkspaceArchiveReadError,
            error_path=root,
        )
        if skip_workspace_root:
            # A mount on `/workspace` has no non-empty relative path to put in the prune set, so
            # skip the copy entirely and preserve only an empty workspace root in the archive.
            await self._exec_checked(
                "mkdir",
                "-p",
                str(staging_workspace),
                error_cls=WorkspaceArchiveReadError,
                error_path=root,
            )
        elif skip_rel_paths:
            await self._exec_checked(
                "mkdir",
                "-p",
                str(staging_workspace),
                error_cls=WorkspaceArchiveReadError,
                error_path=root,
            )
            await self._copy_workspace_tree_pruned(
                src_dir=root,
                dst_dir=staging_workspace,
                rel_dir=Path(),
                skip_rel_paths=skip_rel_paths,
            )
        else:
            await self._exec_checked(
                "cp",
                "-R",
                "--",
                str(root),
                str(staging_workspace),
                error_cls=WorkspaceArchiveReadError,
                error_path=root,
            )
        return staging_parent, staging_workspace

    async def _rm_best_effort(self, path: Path) -> None:
        try:
            await self.exec("rm", "-rf", "--", str(path), shell=False)
        except Exception:
            pass

    async def _exec_checked(
        self,
        *cmd: str | Path,
        error_cls: type[WorkspaceArchiveReadError] | type[WorkspaceArchiveWriteError],
        error_path: Path,
    ) -> ExecResult:
        res = await self.exec(*cmd, shell=False)
        if not res.ok():
            raise error_cls(
                path=error_path,
                context={
                    "command": [str(c) for c in cmd],
                    "stdout": res.stdout.decode("utf-8", errors="replace"),
                    "stderr": res.stderr.decode("utf-8", errors="replace"),
                },
            )
        return res

    async def _ensure_backend_started(self) -> None:
        self._container.reload()
        if not await self.running():
            self._container.start()

    async def _after_start(self) -> None:
        self._workspace_root_ready = True
        self._resume_workspace_probe_pending = False

    def _mark_workspace_root_ready_from_probe(self) -> None:
        super()._mark_workspace_root_ready_from_probe()
        self._workspace_root_ready = True

    async def _exec_run(
        self,
        *,
        cmd: list[str],
        workdir: str | None,
        user: str | None,
        timeout: float | None,
        command_for_errors: tuple[str | Path, ...],
        kill_on_timeout: bool,
    ) -> ExecResult:
        loop = asyncio.get_running_loop()
        future = loop.run_in_executor(
            _DOCKER_EXECUTOR,
            lambda: self._container.exec_run(
                cmd=cmd,
                demux=True,
                workdir=workdir,
                user=user or "",
            ),
        )
        try:
            exec_result = await asyncio.wait_for(future, timeout=timeout)
        except asyncio.TimeoutError as e:
            if kill_on_timeout:
                # Best-effort: kill processes matching the command line.
                # If this fails, the caller still gets a timeout error.
                try:
                    pattern = " ".join(str(c) for c in command_for_errors).replace("'", "'\\''")
                    self._container.exec_run(
                        cmd=[
                            "sh",
                            "-lc",
                            f"pkill -f -- '{pattern}' >/dev/null 2>&1 || true",
                        ],
                        demux=True,
                        user=user or "",
                    )
                except Exception:
                    pass
            raise ExecTimeoutError(command=command_for_errors, timeout_s=timeout, cause=e) from e
        except Exception as e:
            raise ExecTransportError(command=command_for_errors, cause=e) from e

        stdout, stderr = exec_result.output
        stdout_bytes = stdout or b""
        stderr_bytes = stderr or b""
        exit_code = exec_result.exit_code
        if exit_code is None:
            raise ExecTransportError(
                command=command_for_errors,
                context={
                    "reason": "missing_exit_code",
                    "stdout": stdout_bytes.decode("utf-8", errors="replace"),
                    "stderr": stderr_bytes.decode("utf-8", errors="replace"),
                    "workdir": workdir,
                    "retry_safe": True,
                },
            )
        return ExecResult(
            stdout=stdout_bytes,
            stderr=stderr_bytes,
            exit_code=exit_code,
        )

    async def _recover_workspace_root_ready(self, *, timeout: float | None) -> None:
        if self._workspace_root_ready or not self._resume_workspace_probe_pending:
            return

        root = self.state.manifest.root
        probe_command = ("test", "-d", root)
        try:
            result = await self._exec_run(
                cmd=[str(c) for c in probe_command],
                workdir=None,
                user=None,
                timeout=timeout,
                command_for_errors=probe_command,
                kill_on_timeout=False,
            )
        except (ExecTimeoutError, ExecTransportError):
            return
        finally:
            self._resume_workspace_probe_pending = False

        if result.ok():
            self._mark_workspace_root_ready_from_probe()

    @staticmethod
    def _coerce_exec_user(user: str | User | None) -> str | None:
        if isinstance(user, User):
            return user.name
        return user

    async def exec(
        self,
        *command: str | Path,
        timeout: float | None = None,
        shell: bool | list[str] = True,
        user: str | User | None = None,
    ) -> ExecResult:
        if user is None:
            return await super().exec(*command, timeout=timeout, shell=shell, user=None)

        sanitized_command = self._prepare_exec_command(*command, shell=shell, user=None)
        return await self._exec_internal_for_user(
            *sanitized_command,
            timeout=timeout,
            user=self._coerce_exec_user(user),
        )

    async def _exec_internal(
        self, *command: str | Path, timeout: float | None = None
    ) -> ExecResult:
        return await self._exec_internal_for_user(*command, timeout=timeout, user=None)

    async def _exec_internal_for_user(
        self,
        *command: str | Path,
        timeout: float | None = None,
        user: str | None = None,
    ) -> ExecResult:
        # `docker-py` is synchronous and can block indefinitely (e.g. hung
        # process, daemon issues). Run in a worker thread so we can enforce a
        # timeout without requiring `timeout(1)` in the container image.
        # Use a shared bounded executor so repeated timeouts do not leak one
        # new thread per command.
        cmd: list[str] = [str(c) for c in command]
        await self._recover_workspace_root_ready(timeout=timeout)
        # The workspace root is created during `apply_manifest()`, so the first
        # bootstrap commands must not force Docker to chdir there yet.
        workdir = self.state.manifest.root if self._workspace_root_ready else None
        return await self._exec_run(
            cmd=cmd,
            workdir=workdir,
            user=user,
            timeout=timeout,
            command_for_errors=command,
            kill_on_timeout=True,
        )

    async def _stream_into_exec(
        self,
        *,
        cmd: list[str],
        stream: io.IOBase,
        error_path: Path,
        user: str | User | None = None,
    ) -> None:
        def _write() -> int | None:
            container_client = self._container.client
            assert container_client is not None
            api = container_client.api
            resp = api.exec_create(
                self._container.id,
                cmd,
                stdin=True,
                stdout=True,
                stderr=True,
                workdir=None,
                user=self._coerce_exec_user(user) or "",
            )
            exec_socket = self._start_exec_socket(api=api, exec_id=cast(str, resp["Id"]))
            sock = exec_socket.sock
            raw_sock = exec_socket.raw_sock
            try:
                while True:
                    chunk = stream.read(1024 * 1024)
                    if not chunk:
                        break
                    if isinstance(chunk, str):
                        chunk = chunk.encode("utf-8")
                    elif not isinstance(chunk, bytes):
                        chunk = bytes(chunk)
                    if hasattr(raw_sock, "sendall"):
                        raw_sock.sendall(chunk)
                    else:
                        cast(Any, sock).write(chunk)

                try:
                    if hasattr(raw_sock, "shutdown"):
                        raw_sock.shutdown(socket.SHUT_WR)
                    else:
                        cast(Any, sock).flush()
                except Exception:
                    pass

                try:
                    if hasattr(raw_sock, "recv"):
                        while raw_sock.recv(1024 * 1024):
                            pass
                    else:
                        while cast(Any, sock).read(1024 * 1024):
                            pass
                except Exception:
                    pass
            finally:
                exec_socket.close()

            return cast(int | None, api.exec_inspect(resp["Id"]).get("ExitCode"))

        loop = asyncio.get_running_loop()
        try:
            exit_code = await loop.run_in_executor(_DOCKER_EXECUTOR, _write)
        except Exception as e:
            raise WorkspaceArchiveWriteError(path=error_path, cause=e) from e

        if exit_code not in (0, None):
            raise WorkspaceArchiveWriteError(
                path=error_path,
                context={
                    "command": cmd,
                    "exit_code": str(exit_code),
                },
            )

    async def _write_stream_via_exec(
        self,
        *,
        staging_path: Path,
        stream: io.IOBase,
        user: str | User | None = None,
    ) -> None:
        await self._stream_into_exec(
            cmd=["sh", "-lc", 'cat > "$1"', "sh", str(staging_path)],
            stream=stream,
            error_path=staging_path,
            user=user,
        )

    async def _prepare_user_pty_pid_path(self, *, path: Path, user: str | None) -> None:
        if user is None:
            return
        await self._exec_checked(
            "sh",
            "-lc",
            _PREPARE_USER_PTY_PID_SCRIPT,
            "sh",
            str(path),
            user,
            error_cls=WorkspaceArchiveWriteError,
            error_path=path,
        )

    async def read(self, path: Path, *, user: str | User | None = None) -> io.IOBase:
        workspace_path = await self._normalize_path_for_io(path)

        # Read from inside the container instead of `get_archive()`: with Docker
        # volume-driver-backed mounts attached, daemon archive operations can re-run volume mount
        # setup and some plugins reject the duplicate `Mount` call for the same container id.
        res = await self.exec("cat", "--", str(workspace_path), shell=False, user=user)
        if not res.ok():
            raise WorkspaceReadNotFoundError(
                path=path,
                context={
                    "command": ["cat", "--", str(workspace_path)],
                    "stdout": res.stdout.decode("utf-8", errors="replace"),
                    "stderr": res.stderr.decode("utf-8", errors="replace"),
                },
            )
        return io.BytesIO(res.stdout)

    async def write(
        self,
        path: Path,
        data: io.IOBase,
        *,
        user: str | User | None = None,
    ) -> None:
        payload = coerce_write_payload(path=path, data=data)

        path = await self._normalize_path_for_io(path)

        if user is not None:
            await self._stream_into_exec(
                cmd=[
                    "sh",
                    "-lc",
                    'mkdir -p "$(dirname "$1")" && cat > "$1"',
                    "sh",
                    str(path),
                ],
                stream=payload.stream,
                error_path=path,
                user=user,
            )
            return

        parent = path.parent
        await self.mkdir(parent, parents=True)

        # Stream into a temporary file from inside the container, then copy into place.
        # Avoid `put_archive()`: with Docker volume-driver-backed mounts attached, the daemon can
        # re-run volume mount setup during archive operations and some plugins reject the
        # duplicate `Mount` call for the same container id.
        staging_path = self._archive_stage_path(name_hint=path.name)

        await self._exec_checked(
            "mkdir",
            "-p",
            str(self._ARCHIVE_STAGING_DIR),
            error_cls=WorkspaceArchiveWriteError,
            error_path=self._ARCHIVE_STAGING_DIR,
        )

        await self._write_stream_via_exec(
            staging_path=staging_path,
            stream=payload.stream,
        )

        # Copy into place using a process inside the container, which can see mounts.
        cp_res = await self.exec("cp", "--", str(staging_path), str(path), shell=False)
        if not cp_res.ok():
            raise WorkspaceArchiveWriteError(
                path=parent,
                context={
                    "command": ["cp", "--", str(staging_path), str(path)],
                    "stdout": cp_res.stdout.decode("utf-8", errors="replace"),
                    "stderr": cp_res.stderr.decode("utf-8", errors="replace"),
                },
            )

        # Best-effort cleanup. Ignore failures (e.g. concurrent cleanup).
        await self._rm_best_effort(staging_path)

    async def running(self) -> bool:
        # docker-py caches container attributes; refresh to avoid stale status,
        # especially right after start/stop.
        try:
            self._container.reload()
        except docker.errors.APIError:
            # Best-effort: if we can't reload, fall back to last known status.
            pass
        return cast(str, self._container.status) == "running"

    async def _shutdown_backend(self) -> None:
        # Best-effort: stop the container if it exists.
        try:
            self._container.reload()
        except Exception:
            pass
        try:
            if await self.running():
                self._container.stop()
        except Exception:
            # If the container is already gone/stopped, ignore.
            pass

    @staticmethod
    def _start_exec_socket(*, api: Any, exec_id: str, tty: bool = False) -> _DockerExecSocket:
        if not all(
            callable(getattr(api, attr, None))
            for attr in ("_post_json", "_url", "_get_raw_response_socket")
        ):
            sock = api.exec_start(exec_id, socket=True, tty=tty)
            return _DockerExecSocket(sock=sock, raw_sock=getattr(sock, "_sock", sock))

        response = api._post_json(
            api._url("/exec/{0}/start", exec_id),
            headers={"Connection": "Upgrade", "Upgrade": "tcp"},
            data={"Tty": tty, "Detach": False},
            stream=True,
        )
        sock = api._get_raw_response_socket(response)
        raw_sock = getattr(sock, "_sock", sock)
        return _DockerExecSocket(sock=sock, raw_sock=raw_sock, response=response)

    async def pty_exec_start(
        self,
        *command: str | Path,
        timeout: float | None = None,
        shell: bool | list[str] = True,
        user: str | User | None = None,
        tty: bool = False,
        yield_time_s: float | None = None,
        max_output_tokens: int | None = None,
    ) -> PtyExecUpdate:
        docker_user = self._coerce_exec_user(user)
        sanitized_command = self._prepare_exec_command(*command, shell=shell, user=None)
        cmd = [str(c) for c in sanitized_command]
        await self._recover_workspace_root_ready(timeout=timeout)
        workdir = self.state.manifest.root if self._workspace_root_ready else None

        loop = asyncio.get_running_loop()
        container_client = self._container.client
        assert container_client is not None
        api = container_client.api

        entry: _DockerPtyProcessEntry | None = None
        pty_pid_path: Path | None = None
        registered = False
        pruned_entry: _DockerPtyProcessEntry | None = None
        process_id = 0
        process_count = 0

        try:
            pty_pid_path = self._archive_stage_path(name_hint="pty.pid")
            await self._prepare_user_pty_pid_path(path=pty_pid_path, user=docker_user)
            wrapped_cmd = [
                "sh",
                "-lc",
                'mkdir -p "$1" && printf "%s" "$$" > "$2" && shift 2 && exec "$@"',
                "sh",
                str(pty_pid_path.parent),
                str(pty_pid_path),
                *cmd,
            ]
            resp = await asyncio.wait_for(
                loop.run_in_executor(
                    _DOCKER_EXECUTOR,
                    lambda: api.exec_create(
                        self._container.id,
                        wrapped_cmd,
                        stdin=True,
                        stdout=True,
                        stderr=True,
                        tty=tty,
                        workdir=workdir,
                        user=docker_user or "",
                    ),
                ),
                timeout=timeout,
            )
            exec_id = cast(str, resp["Id"])
            exec_socket = await asyncio.wait_for(
                loop.run_in_executor(
                    _DOCKER_EXECUTOR,
                    lambda: self._start_exec_socket(api=api, exec_id=exec_id, tty=tty),
                ),
                timeout=timeout,
            )
            raw_sock = exec_socket.raw_sock
            if not tty:
                try:
                    cast(Any, raw_sock).shutdown(socket.SHUT_WR)
                except Exception:
                    pass
            entry = _DockerPtyProcessEntry(
                exec_id=exec_id,
                sock=exec_socket,
                raw_sock=raw_sock,
                pid_path=pty_pid_path,
                tty=tty,
            )
            entry.reader_thread = threading.Thread(
                target=self._pump_pty_socket,
                args=(entry, loop),
                daemon=True,
                name=f"agents-docker-pty-{exec_id[:12]}",
            )
            entry.reader_thread.start()
            entry.wait_task = asyncio.create_task(self._watch_pty_exit(entry))

            async with self._pty_lock:
                process_id = allocate_pty_process_id(self._reserved_pty_process_ids)
                self._reserved_pty_process_ids.add(process_id)
                pruned_entry = self._prune_pty_processes_if_needed()
                self._pty_processes[process_id] = entry
                process_count = len(self._pty_processes)
                registered = True
        except asyncio.TimeoutError as e:
            if entry is not None and not registered:
                await self._terminate_pty_entry(entry)
            elif pty_pid_path is not None:
                await self._kill_pty_pid_path(pty_pid_path)
            raise ExecTimeoutError(command=command, timeout_s=timeout, cause=e) from e
        except Exception as e:
            if entry is not None and not registered:
                await self._terminate_pty_entry(entry)
            raise ExecTransportError(
                command=command,
                context={"retry_safe": True},
                cause=e,
            ) from e
        except BaseException:
            if entry is not None and not registered:
                await self._terminate_pty_entry(entry)
            raise

        if pruned_entry is not None:
            await self._terminate_pty_entry(pruned_entry)

        if process_count >= PTY_PROCESSES_WARNING:
            logger.warning(
                "PTY process count reached warning threshold: %s active sessions",
                process_count,
            )

        yield_time_ms = 10_000 if yield_time_s is None else int(yield_time_s * 1000)
        output, original_token_count = await self._collect_pty_output(
            entry=entry,
            yield_time_ms=clamp_pty_yield_time_ms(yield_time_ms),
            max_output_tokens=max_output_tokens,
        )
        return await self._finalize_pty_update(
            process_id=process_id,
            entry=entry,
            output=output,
            original_token_count=original_token_count,
        )

    async def pty_write_stdin(
        self,
        *,
        session_id: int,
        chars: str,
        yield_time_s: float | None = None,
        max_output_tokens: int | None = None,
    ) -> PtyExecUpdate:
        async with self._pty_lock:
            entry = self._resolve_pty_session_entry(
                pty_processes=self._pty_processes,
                session_id=session_id,
            )

        if chars:
            if not entry.tty:
                raise RuntimeError("stdin is not available for this process")
            loop = asyncio.get_running_loop()
            payload = chars.encode("utf-8")
            try:
                await loop.run_in_executor(
                    _DOCKER_EXECUTOR,
                    lambda: cast(Any, entry.raw_sock).sendall(payload),
                )
            except (BrokenPipeError, OSError) as e:
                if not isinstance(e, BrokenPipeError) and e.errno not in {
                    errno.EPIPE,
                    errno.EBADF,
                    errno.ECONNRESET,
                }:
                    raise
            await asyncio.sleep(0.1)

        yield_time_ms = 250 if yield_time_s is None else int(yield_time_s * 1000)
        output, original_token_count = await self._collect_pty_output(
            entry=entry,
            yield_time_ms=resolve_pty_write_yield_time_ms(
                yield_time_ms=yield_time_ms, input_empty=chars == ""
            ),
            max_output_tokens=max_output_tokens,
        )
        entry.last_used = time.monotonic()
        return await self._finalize_pty_update(
            process_id=session_id,
            entry=entry,
            output=output,
            original_token_count=original_token_count,
        )

    async def pty_terminate_all(self) -> None:
        async with self._pty_lock:
            entries = list(self._pty_processes.values())
            self._pty_processes.clear()
            self._reserved_pty_process_ids.clear()

        for entry in entries:
            await self._terminate_pty_entry(entry)

    def _pump_pty_socket(
        self, entry: _DockerPtyProcessEntry, loop: asyncio.AbstractEventLoop
    ) -> None:
        try:
            for stream_id, chunk in docker_socket.frames_iter(entry.raw_sock, tty=entry.tty):
                _ = stream_id
                future = asyncio.run_coroutine_threadsafe(
                    self._append_pty_output_chunks(entry, [bytes(chunk)]),
                    loop,
                )
                future.result()
        except Exception:
            pass
        finally:
            future = asyncio.run_coroutine_threadsafe(
                self._mark_pty_output_closed(entry),
                loop,
            )
            try:
                future.result()
            except Exception:
                pass

    async def _append_pty_output_chunks(
        self, entry: _DockerPtyProcessEntry, chunks: list[bytes]
    ) -> None:
        async with entry.output_lock:
            entry.output_chunks.extend(chunks)
        entry.output_notify.set()

    async def _mark_pty_output_closed(self, entry: _DockerPtyProcessEntry) -> None:
        entry.output_closed.set()
        entry.output_notify.set()

    async def _watch_pty_exit(self, entry: _DockerPtyProcessEntry) -> None:
        loop = asyncio.get_running_loop()
        container_client = self._container.client
        if container_client is None:
            entry.output_notify.set()
            return
        api = container_client.api

        while True:
            try:
                inspect_result = await loop.run_in_executor(
                    _DOCKER_EXECUTOR,
                    lambda: api.exec_inspect(entry.exec_id),
                )
            except Exception:
                break

            if not inspect_result.get("Running", False):
                exit_code = inspect_result.get("ExitCode")
                if exit_code is not None:
                    entry.exit_code = int(exit_code)
                break

            await asyncio.sleep(0.05)

        entry.output_notify.set()

    async def _refresh_pty_exit_code(self, entry: _DockerPtyProcessEntry) -> None:
        if entry.exit_code is not None:
            return

        loop = asyncio.get_running_loop()
        container_client = self._container.client
        if container_client is None:
            return
        api = container_client.api

        try:
            inspect_result = await loop.run_in_executor(
                _DOCKER_EXECUTOR,
                lambda: api.exec_inspect(entry.exec_id),
            )
        except Exception:
            return

        if inspect_result.get("Running", False):
            return

        exit_code = inspect_result.get("ExitCode")
        if exit_code is not None:
            entry.exit_code = int(exit_code)

    async def _collect_pty_output(
        self,
        *,
        entry: _DockerPtyProcessEntry,
        yield_time_ms: int,
        max_output_tokens: int | None,
    ) -> tuple[bytes, int | None]:
        deadline = time.monotonic() + (yield_time_ms / 1000)
        output = bytearray()

        while True:
            async with entry.output_lock:
                while entry.output_chunks:
                    output.extend(entry.output_chunks.popleft())

            if time.monotonic() >= deadline:
                break

            if entry.output_closed.is_set():
                async with entry.output_lock:
                    while entry.output_chunks:
                        output.extend(entry.output_chunks.popleft())
                break

            remaining_s = deadline - time.monotonic()
            if remaining_s <= 0:
                break

            try:
                await asyncio.wait_for(entry.output_notify.wait(), timeout=remaining_s)
            except asyncio.TimeoutError:
                break
            entry.output_notify.clear()

        text = output.decode("utf-8", errors="replace")
        truncated_text, original_token_count = truncate_text_by_tokens(text, max_output_tokens)
        return truncated_text.encode("utf-8", errors="replace"), original_token_count

    async def _finalize_pty_update(
        self,
        *,
        process_id: int,
        entry: _DockerPtyProcessEntry,
        output: bytes,
        original_token_count: int | None,
    ) -> PtyExecUpdate:
        if entry.output_closed.is_set() and entry.exit_code is None:
            await self._refresh_pty_exit_code(entry)

        exit_code = entry.exit_code
        live_process_id: int | None = process_id

        if exit_code is not None:
            async with self._pty_lock:
                removed = self._pty_processes.pop(process_id, None)
                self._reserved_pty_process_ids.discard(process_id)
            if removed is not None:
                await self._terminate_pty_entry(removed)
            live_process_id = None

        return PtyExecUpdate(
            process_id=live_process_id,
            output=output,
            exit_code=exit_code,
            original_token_count=original_token_count,
        )

    def _prune_pty_processes_if_needed(self) -> _DockerPtyProcessEntry | None:
        if len(self._pty_processes) < PTY_PROCESSES_MAX:
            return None

        meta = [
            (process_id, entry.last_used, entry.exit_code is not None)
            for process_id, entry in self._pty_processes.items()
        ]
        process_id = process_id_to_prune_from_meta(meta)
        if process_id is None:
            return None

        self._reserved_pty_process_ids.discard(process_id)
        return self._pty_processes.pop(process_id, None)

    async def _terminate_pty_entry(self, entry: _DockerPtyProcessEntry) -> None:
        if entry.wait_task is not None:
            entry.wait_task.cancel()

        await self._refresh_pty_exit_code(entry)

        if entry.exit_code is None:
            await self._kill_pty_pid_path(entry.pid_path)
        else:
            await self._rm_best_effort(entry.pid_path)

        try:
            cast(Any, entry.sock).close()
        except Exception:
            pass

        if entry.reader_thread is not None:
            await asyncio.to_thread(entry.reader_thread.join, 1.0)

        await asyncio.gather(
            *(task for task in (entry.wait_task,) if task is not None),
            return_exceptions=True,
        )

    async def _kill_pty_pid_path(self, pid_path: Path) -> None:
        loop = asyncio.get_running_loop()
        try:
            await loop.run_in_executor(
                _DOCKER_EXECUTOR,
                lambda: self._container.exec_run(
                    cmd=[
                        "sh",
                        "-lc",
                        (
                            'if [ -f "$1" ]; then '
                            'pid="$(cat "$1" 2>/dev/null || true)"; '
                            'if [ -n "$pid" ]; then '
                            'kill -KILL "$pid" >/dev/null 2>&1 || true; '
                            "fi; "
                            "fi"
                        ),
                        "sh",
                        str(pid_path),
                    ],
                    demux=True,
                ),
            )
        except Exception:
            pass

        await self._rm_best_effort(pid_path)

    async def exists(self) -> bool:
        try:
            self._docker_client.containers.get(self.state.container_id)
            return True
        except docker.errors.NotFound:
            return False

    @retry_async(
        retry_if=lambda exc, self: exception_chain_has_status_code(exc, TRANSIENT_HTTP_STATUS_CODES)
    )
    async def persist_workspace(self) -> io.IOBase:
        skip = self._persist_workspace_skip_relpaths()
        root = Path(self.state.manifest.root)
        try:
            staging_parent, staging_workspace = await self._stage_workspace_copy(
                skip_rel_paths=skip
            )
            root_prefixed_archive = self._workspace_archive_stream(
                staging_workspace,
                cleanup_path=staging_parent,
            )
            return strip_tar_member_prefix(root_prefixed_archive, prefix=staging_workspace.name)
        except docker.errors.NotFound as e:
            raise WorkspaceArchiveReadError(path=root, cause=e) from e
        except docker.errors.APIError as e:
            raise WorkspaceArchiveReadError(path=root, cause=e) from e

    async def hydrate_workspace(self, data: io.IOBase) -> None:
        root = Path(self.state.manifest.root)
        with tempfile.TemporaryFile() as archive:
            while True:
                chunk = data.read(io.DEFAULT_BUFFER_SIZE)
                if chunk in ("", b""):
                    break
                if isinstance(chunk, str):
                    chunk = chunk.encode("utf-8")
                if not isinstance(chunk, bytes | bytearray):
                    raise WorkspaceArchiveWriteError(
                        path=root,
                        context={"reason": "non_bytes_tar_payload"},
                    )
                archive.write(chunk)

            try:
                archive.seek(0)
                with tarfile.open(fileobj=archive, mode="r:*") as tar:
                    validate_tarfile(tar)
            except UnsafeTarMemberError as e:
                raise WorkspaceArchiveWriteError(
                    path=root,
                    context={"reason": e.reason, "member": e.member},
                    cause=e,
                ) from e
            except (tarfile.TarError, OSError) as e:
                raise WorkspaceArchiveWriteError(path=root, cause=e) from e

            await self._exec_checked(
                "mkdir",
                "-p",
                str(root),
                error_cls=WorkspaceArchiveWriteError,
                error_path=root,
            )
            archive.seek(0)
            await self._stream_into_exec(
                cmd=["tar", "-x", "-C", str(root)],
                stream=archive,
                error_path=root,
            )

    def _schedule_rm_best_effort(self, path: Path) -> None:
        loop = asyncio.get_running_loop()
        loop.create_task(self._rm_best_effort(path))

    def _workspace_archive_stream(
        self,
        path: Path,
        *,
        cleanup_path: Path | None = None,
    ) -> io.IOBase:
        on_close = (
            (lambda: self._schedule_rm_best_effort(cleanup_path))
            if cleanup_path is not None
            else None
        )
        container_client = getattr(self._container, "client", None)
        api = getattr(container_client, "api", None)
        if api is None:
            bits, _ = self._container.get_archive(str(path))
            return IteratorIO(it=cast(Iterator[bytes], bits), on_close=on_close)

        url = api._url("/containers/{0}/archive", self._container.id)
        response = api._get(
            url,
            params={"path": str(path)},
            stream=True,
            headers={"Accept-Encoding": "identity"},
        )
        api._raise_for_status(response)
        return IteratorIO(it=self._iter_archive_chunks(api, response), on_close=on_close)

    @staticmethod
    def _iter_archive_chunks(api: Any, response: Any) -> Iterator[bytes]:
        try:
            yield from api._stream_raw_result(
                response,
                chunk_size=DEFAULT_DATA_CHUNK_SIZE,
                decode=False,
            )
        finally:
            try:
                response.close()
            except Exception:
                pass

supports_docker_volume_mounts

supports_docker_volume_mounts() -> bool

Docker attaches volume-driver mounts when creating the container.

Source code in src/agents/sandbox/sandboxes/docker.py
def supports_docker_volume_mounts(self) -> bool:
    """Docker attaches volume-driver mounts when creating the container."""

    return True

stop async

stop() -> None

Persist/snapshot the workspace.

Note: stop() is intentionally persistence-only. Sandboxes that need to tear down sandbox resources (Docker containers, remote sessions, etc.) should implement shutdown() instead.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def stop(self) -> None:
    """
    Persist/snapshot the workspace.

    Note: `stop()` is intentionally persistence-only. Sandboxes that need to tear down
    sandbox resources (Docker containers, remote sessions, etc.) should implement
    `shutdown()` instead.
    """
    try:
        try:
            await self._before_stop()
            await self._persist_snapshot()
        except Exception as e:
            wrapped = self._wrap_stop_error(e)
            if wrapped is e:
                raise
            raise wrapped from e
    finally:
        await self._after_stop()

shutdown async

shutdown() -> None

Tear down sandbox resources (best-effort).

Default is a no-op. Sandbox-specific sessions (e.g. Docker) should override.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def shutdown(self) -> None:
    """
    Tear down sandbox resources (best-effort).

    Default is a no-op. Sandbox-specific sessions (e.g. Docker) should override.
    """
    await self._before_shutdown()
    await self._shutdown_backend()
    await self._after_shutdown()

aclose async

aclose() -> None

Run the session cleanup lifecycle outside of async with.

This performs the same session-owned cleanup as __aexit__(): persist/snapshot the workspace via stop(), tear down session resources via shutdown(), and close session-scoped dependencies. If the session came from a sandbox client, call the client's delete() separately for backend-specific deletion such as removing a Docker container or deleting a temporary host workspace.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def aclose(self) -> None:
    """Run the session cleanup lifecycle outside of ``async with``.

    This performs the same session-owned cleanup as ``__aexit__()``: persist/snapshot the
    workspace via ``stop()``, tear down session resources via ``shutdown()``, and close
    session-scoped dependencies. If the session came from a sandbox client, call the client's
    ``delete()`` separately for backend-specific deletion such as removing a Docker container
    or deleting a temporary host workspace.
    """
    try:
        await self.run_pre_stop_hooks()
        await self.stop()
        await self.shutdown()
    finally:
        await self._aclose_dependencies()

register_pre_stop_hook

register_pre_stop_hook(
    hook: Callable[[], Awaitable[None]],
) -> None

Register an async hook to run once before the session workspace is persisted.

Source code in src/agents/sandbox/session/base_sandbox_session.py
def register_pre_stop_hook(self, hook: Callable[[], Awaitable[None]]) -> None:
    """Register an async hook to run once before the session workspace is persisted."""

    hooks = self._pre_stop_hooks
    if hooks is None:
        hooks = []
        self._pre_stop_hooks = hooks
    hooks.append(hook)
    self._pre_stop_hooks_ran = False

run_pre_stop_hooks async

run_pre_stop_hooks() -> None

Run registered pre-stop hooks once before workspace persistence.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def run_pre_stop_hooks(self) -> None:
    """Run registered pre-stop hooks once before workspace persistence."""

    hooks = self._pre_stop_hooks
    if hooks is None or self._pre_stop_hooks_ran:
        return
    self._pre_stop_hooks_ran = True
    cleanup_error: BaseException | None = None
    for hook in hooks:
        try:
            await hook()
        except BaseException as exc:
            if cleanup_error is None:
                cleanup_error = exc
    if cleanup_error is not None:
        raise cleanup_error

register_persist_workspace_skip_path

register_persist_workspace_skip_path(
    path: Path | str,
) -> Path

Exclude a runtime-created workspace path from future workspace snapshots.

Use this for session side effects that are not part of durable workspace state, such as generated mount config or ephemeral sink output.

Source code in src/agents/sandbox/session/base_sandbox_session.py
def register_persist_workspace_skip_path(self, path: Path | str) -> Path:
    """Exclude a runtime-created workspace path from future workspace snapshots.

    Use this for session side effects that are not part of durable workspace state, such as
    generated mount config or ephemeral sink output.
    """

    rel_path = Manifest._coerce_rel_path(path)
    Manifest._validate_rel_path(rel_path)
    if rel_path in (Path(""), Path(".")):
        raise ValueError("Persist workspace skip paths must target a concrete relative path.")
    overlapping_mounts = self._overlapping_mount_relpaths(rel_path)
    if overlapping_mounts:
        overlapping_mount = min(overlapping_mounts, key=lambda p: (len(p.parts), p.as_posix()))
        raise MountConfigError(
            message="persist workspace skip path must not overlap mount path",
            context={
                "skip_path": rel_path.as_posix(),
                "mount_path": overlapping_mount.as_posix(),
            },
        )

    if self._runtime_persist_workspace_skip_relpaths is None:
        self._runtime_persist_workspace_skip_relpaths = set()
    self._runtime_persist_workspace_skip_relpaths.add(rel_path)
    return rel_path

ls async

ls(
    path: Path | str, *, user: str | User | None = None
) -> list[FileEntry]

List directory contents.

:param path: Path to list. :param user: Optional sandbox user to list as. :returns: A list of FileEntry objects.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def ls(
    self,
    path: Path | str,
    *,
    user: str | User | None = None,
) -> list[FileEntry]:
    """List directory contents.

    :param path: Path to list.
    :param user: Optional sandbox user to list as.
    :returns: A list of `FileEntry` objects.
    """
    path = await self._normalize_path_for_io(path)

    cmd = ("ls", "-la", "--", str(path))
    result = await self.exec(*cmd, shell=False, user=user)
    if not result.ok():
        raise ExecNonZeroError(result, command=cmd)

    return parse_ls_la(result.stdout.decode("utf-8", errors="replace"), base=str(path))

rm async

rm(
    path: Path | str,
    *,
    recursive: bool = False,
    user: str | User | None = None,
) -> None

Remove a file or directory.

:param path: Path to remove. :param recursive: If true, remove directories recursively. :param user: Optional sandbox user to remove as.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def rm(
    self,
    path: Path | str,
    *,
    recursive: bool = False,
    user: str | User | None = None,
) -> None:
    """Remove a file or directory.

    :param path: Path to remove.
    :param recursive: If true, remove directories recursively.
    :param user: Optional sandbox user to remove as.
    """
    path = await self._normalize_path_for_io(path)

    cmd: list[str] = ["rm"]
    if recursive:
        cmd.append("-rf")
    cmd.extend(["--", str(path)])

    result = await self.exec(*cmd, shell=False, user=user)
    if not result.ok():
        raise ExecNonZeroError(result, command=cmd)

mkdir async

mkdir(
    path: Path | str,
    *,
    parents: bool = False,
    user: str | User | None = None,
) -> None

Create a directory.

:param path: Directory to create on the remote. :param parents: If true, create missing parents. :param user: Optional sandbox user to create the directory as.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def mkdir(
    self,
    path: Path | str,
    *,
    parents: bool = False,
    user: str | User | None = None,
) -> None:
    """Create a directory.

    :param path: Directory to create on the remote.
    :param parents: If true, create missing parents.
    :param user: Optional sandbox user to create the directory as.
    """
    path = await self._normalize_path_for_io(path)

    cmd: list[str] = ["mkdir"]
    if parents:
        cmd.append("-p")
    cmd.append(str(path))

    result = await self.exec(*cmd, shell=False, user=user)
    if not result.ok():
        raise ExecNonZeroError(result, command=cmd)

extract async

extract(
    path: Path | str,
    data: IOBase,
    *,
    compression_scheme: Literal["tar", "zip"] | None = None,
) -> None

Write a compressed archive to a destination on the remote. Optionally extract the archive once written.

:param path: Path on the host machine to extract to :param data: a file-like io stream. :param compression_scheme: either "tar" or "zip". If not provided, it will try to infer from the path.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def extract(
    self,
    path: Path | str,
    data: io.IOBase,
    *,
    compression_scheme: Literal["tar", "zip"] | None = None,
) -> None:
    """
    Write a compressed archive to a destination on the remote.
    Optionally extract the archive once written.

    :param path: Path on the host machine to extract to
    :param data: a file-like io stream.
    :param compression_scheme: either "tar" or "zip". If not provided,
        it will try to infer from the path.
    """
    if isinstance(path, str):
        path = Path(path)

    if compression_scheme is None:
        suffix = path.suffix.removeprefix(".")
        compression_scheme = cast(Literal["tar", "zip"], suffix) if suffix else None

    if compression_scheme is None or compression_scheme not in ["zip", "tar"]:
        raise InvalidCompressionSchemeError(path=path, scheme=compression_scheme)

    normalized_path = await self._normalize_path_for_io(path)
    destination_root = normalized_path.parent

    # Materialize the archive into a local spool once because both `write()` and the
    # extraction step consume the stream, and zip extraction may require seeking.
    spool = tempfile.SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode="w+b")
    try:
        shutil.copyfileobj(data, spool)
        spool.seek(0)
        await self.write(normalized_path, spool)
        spool.seek(0)

        if compression_scheme == "tar":
            await self._extract_tar_archive(
                archive_path=normalized_path,
                destination_root=destination_root,
                data=spool,
            )
        else:
            await self._extract_zip_archive(
                archive_path=normalized_path,
                destination_root=destination_root,
                data=spool,
            )
    finally:
        spool.close()

should_provision_manifest_accounts_on_resume

should_provision_manifest_accounts_on_resume() -> bool

Return whether resume should reprovision manifest-managed users and groups.

Source code in src/agents/sandbox/session/base_sandbox_session.py
def should_provision_manifest_accounts_on_resume(self) -> bool:
    """Return whether resume should reprovision manifest-managed users and groups."""

    return not self._system_state_preserved_on_start()

DockerSandboxSessionState

Bases: SandboxSessionState

Source code in src/agents/sandbox/sandboxes/docker.py
class DockerSandboxSessionState(SandboxSessionState):
    type: Literal["docker"] = "docker"
    image: str
    container_id: str

__pydantic_init_subclass__ classmethod

__pydantic_init_subclass__(**kwargs: Any) -> None

Auto-register every subclass by its type field default.

Source code in src/agents/sandbox/session/sandbox_session_state.py
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """Auto-register every subclass by its ``type`` field default."""
    super().__pydantic_init_subclass__(**kwargs)

    type_field = cls.model_fields.get("type")
    if type_field is None:
        return

    annotation = type_field.annotation
    if get_origin(annotation) is not Literal:
        return

    args = get_args(annotation)
    if not args:
        return

    type_default = type_field.default
    if not isinstance(type_default, str) or type_default == "":
        return

    SandboxSessionState._subclass_registry[type_default] = cls

parse classmethod

parse(payload: object) -> SandboxSessionState

Deserialize payload into the correct registered subclass.

Accepts a SandboxSessionState instance (returned as-is if already a subclass, or upgraded via model_dump -> registry lookup if it is a bare base instance) or a plain dict.

Source code in src/agents/sandbox/session/sandbox_session_state.py
@classmethod
def parse(cls, payload: object) -> SandboxSessionState:
    """Deserialize *payload* into the correct registered subclass.

    Accepts a ``SandboxSessionState`` instance (returned as-is if already a
    subclass, or upgraded via ``model_dump`` -> registry lookup if it is a
    bare base instance) or a plain ``dict``.
    """
    if isinstance(payload, SandboxSessionState):
        if type(payload) is not SandboxSessionState:
            return payload
        payload = payload.model_dump()

    if isinstance(payload, dict):
        state_type = payload.get("type")
        if not isinstance(state_type, str):
            raise ValueError("sandbox session state payload must include a string `type`")

        subclass = SandboxSessionState._subclass_registry.get(state_type)
        if subclass is None:
            raise ValueError(f"unknown sandbox session state type `{state_type}`")

        return subclass.model_validate(payload)

    raise TypeError("session state payload must be a SandboxSessionState or dict")