Skip to content

Unix local sandbox

UnixLocalSandboxClient

Bases: BaseSandboxClient[UnixLocalSandboxClientOptions | None]

Create local host sessions for trusted development or externally isolated execution.

Linux sessions add no OS-level command confinement. macOS sessions apply filesystem restrictions through sandbox-exec, but do not provide network isolation. Separate workspaces and host environment filtering do not establish an OS isolation boundary. For untrusted commands, including commands influenced by untrusted inputs, use an appropriately configured Docker or hosted backend, or provide external isolation.

Source code in src/agents/sandbox/sandboxes/unix_local.py
class UnixLocalSandboxClient(BaseSandboxClient[UnixLocalSandboxClientOptions | None]):
    """Create local host sessions for trusted development or externally isolated execution.

    Linux sessions add no OS-level command confinement. macOS sessions apply filesystem
    restrictions through sandbox-exec, but do not provide network isolation. Separate
    workspaces and host environment filtering do not establish an OS isolation boundary.
    For untrusted commands, including commands influenced by untrusted inputs, use an
    appropriately configured Docker or hosted backend, or provide external isolation.
    """

    backend_id = "unix_local"
    supports_default_options = True
    _instrumentation: Instrumentation

    def __init__(
        self,
        *,
        instrumentation: Instrumentation | None = None,
        dependencies: Dependencies | None = None,
        inherit_host_environment: bool = True,
        host_environment_allowlist: Collection[str] | None = None,
    ) -> None:
        if inherit_host_environment and host_environment_allowlist is not None:
            raise ValueError("host_environment_allowlist requires inherit_host_environment=False")
        if isinstance(host_environment_allowlist, str):
            raise TypeError("host_environment_allowlist must be a collection of variable names")

        self._instrumentation = (
            instrumentation if instrumentation is not None else Instrumentation()
        )
        self._dependencies = dependencies
        if inherit_host_environment:
            self._host_environment_allowlist = None
        else:
            self._host_environment_allowlist = frozenset(
                _HOST_ENVIRONMENT_ALLOWLIST
                if host_environment_allowlist is None
                else host_environment_allowlist
            )

    @redact_mount_error_data
    async def create(
        self,
        *,
        snapshot: SnapshotSpec | SnapshotBase | None = None,
        manifest: Manifest | None = None,
        options: UnixLocalSandboxClientOptions | None = None,
    ) -> SandboxSession:
        resolved_options = options if options is not None else UnixLocalSandboxClientOptions()
        manifest = manifest if manifest is not None else Manifest()
        _assert_unix_local_host_path_grants_unsupported(manifest)
        self._validate_manifest_for_create(manifest)
        # For local execution, runner-created sessions should always get a dedicated temp root
        # unless the caller explicitly chose a custom host path.
        workspace_root_owned = False
        if manifest.root == _DEFAULT_MANIFEST_ROOT:
            workspace_dir = tempfile.mkdtemp(prefix=_DEFAULT_WORKSPACE_PREFIX)
            workspace_root_owned = True
            manifest = manifest.model_copy(update={"root": workspace_dir}, deep=True)

        session_id = uuid.uuid4()
        snapshot_id = str(session_id)
        snapshot_instance = resolve_snapshot(snapshot, snapshot_id)
        state = UnixLocalSandboxSessionState(
            session_id=session_id,
            manifest=manifest,
            snapshot=snapshot_instance,
            workspace_root_owned=workspace_root_owned,
            exposed_ports=resolved_options.exposed_ports,
        )
        inner = UnixLocalSandboxSession.from_state(state)
        # Keep host inheritance policy under trusted runtime control. Session state and manifests
        # must not be able to change it when a session is resumed by another client.
        inner._host_environment_allowlist = self._host_environment_allowlist
        return self._wrap_session(inner, instrumentation=self._instrumentation)

    async def delete(self, session: SandboxSession) -> SandboxSession:
        """Best-effort cleanup of the on-disk workspace directory."""
        inner = session._inner
        if not isinstance(inner, UnixLocalSandboxSession):
            raise TypeError("UnixLocalSandboxClient.delete expects a UnixLocalSandboxSession")
        if not inner.state.workspace_root_owned:
            return session
        unmount_failed = False
        for mount_entry, mount_path in inner.state.manifest.ephemeral_mount_targets():
            try:
                await mount_entry.unmount(inner, mount_path, Path("/"))
            except Exception as exc:
                unmount_failed = True
                log_tool_action_warning(
                    logger,
                    "Failed to unmount UnixLocal workspace mount before deleting root",
                    exc,
                    diagnostic_extra=partial(_mount_path_diagnostic_extra, mount_path),
                )
        if unmount_failed:
            return session
        try:
            await run_blocking_workspace_io(shutil.rmtree, Path(inner.state.manifest.root))
        except FileNotFoundError:
            pass
        except Exception:
            pass
        return session

    @redact_mount_error_data
    async def resume(
        self,
        state: SandboxSessionState,
    ) -> SandboxSession:
        if not isinstance(state, UnixLocalSandboxSessionState):
            raise TypeError("UnixLocalSandboxClient.resume expects a UnixLocalSandboxSessionState")
        state.assert_path_grants_rebound()
        _assert_unix_local_host_path_grants_unsupported(state.manifest)
        inner = UnixLocalSandboxSession.from_state(state)
        inner._host_environment_allowlist = self._host_environment_allowlist
        return self._wrap_session(inner, instrumentation=self._instrumentation)

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

delete async

delete(session: SandboxSession) -> SandboxSession

Best-effort cleanup of the on-disk workspace directory.

Source code in src/agents/sandbox/sandboxes/unix_local.py
async def delete(self, session: SandboxSession) -> SandboxSession:
    """Best-effort cleanup of the on-disk workspace directory."""
    inner = session._inner
    if not isinstance(inner, UnixLocalSandboxSession):
        raise TypeError("UnixLocalSandboxClient.delete expects a UnixLocalSandboxSession")
    if not inner.state.workspace_root_owned:
        return session
    unmount_failed = False
    for mount_entry, mount_path in inner.state.manifest.ephemeral_mount_targets():
        try:
            await mount_entry.unmount(inner, mount_path, Path("/"))
        except Exception as exc:
            unmount_failed = True
            log_tool_action_warning(
                logger,
                "Failed to unmount UnixLocal workspace mount before deleting root",
                exc,
                diagnostic_extra=partial(_mount_path_diagnostic_extra, mount_path),
            )
    if unmount_failed:
        return session
    try:
        await run_blocking_workspace_io(shutil.rmtree, Path(inner.state.manifest.root))
    except FileNotFoundError:
        pass
    except Exception:
        pass
    return session

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
@redact_mount_error_data_sync
def serialize_session_state(self, state: SandboxSessionState) -> dict[str, object]:
    """Serialize backend-specific sandbox state into a JSON-compatible payload."""
    from ...exceptions import _raise_data_redacted_error
    from .._mount_security import (
        _manifest_has_configured_mount_authority,
        _manifest_mount_provenance_error,
        _mark_mount_validation_error,
        _redact_mount_serialization_error,
    )

    provenance_error = _manifest_mount_provenance_error(state.manifest)
    if provenance_error is not None:
        _mark_mount_validation_error(provenance_error)
        state = cast(Any, None)
        _raise_data_redacted_error(provenance_error)

    try:
        return self._serialize_session_state(state)
    except MountConfigError:
        raise
    except Exception as error:
        if not _manifest_has_configured_mount_authority(state.manifest):
            raise
        raise _redact_mount_serialization_error(error) from None

UnixLocalSandboxClientOptions

Bases: BaseSandboxClientOptions

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

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

UnixLocalSandboxSession

Bases: BaseSandboxSession

Unix-only session implementation that runs commands on the host and uses the host filesystem as the workspace (rooted at self.state.manifest.root).

On Linux, commands run without OS-level confinement added by this backend. On macOS, commands use sandbox-exec filesystem restrictions, which do not provide network isolation. Workspace paths and SDK file API guards do not confine arbitrary Linux shell commands. Use this backend for trusted local execution or within externally provided isolation.

User-scoped listing and writing require sudo access to a system python3 and its standard library. These operations run a trusted file worker in Python isolated mode, independently of the application's interpreter or virtual environment.

Source code in src/agents/sandbox/sandboxes/unix_local.py
 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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
class UnixLocalSandboxSession(BaseSandboxSession):
    """
    Unix-only session implementation that runs commands on the host and uses the host filesystem
    as the workspace (rooted at `self.state.manifest.root`).

    On Linux, commands run without OS-level confinement added by this backend. On macOS,
    commands use sandbox-exec filesystem restrictions, which do not provide network isolation.
    Workspace paths and SDK file API guards do not confine arbitrary Linux shell commands.
    Use this backend for trusted local execution or within externally provided isolation.

    User-scoped listing and writing require sudo access to a system python3 and its standard
    library. These operations run a trusted file worker in Python isolated mode, independently
    of the application's interpreter or virtual environment.
    """

    state: UnixLocalSandboxSessionState
    _running: bool
    _pty_lock: asyncio.Lock
    _pty_processes: dict[int, _UnixPtyProcessEntry]
    _reserved_pty_process_ids: set[int]
    _fd_close_tasks: set[asyncio.Task[None]]
    _host_environment_allowlist: frozenset[str] | None

    def __init__(self, *, state: UnixLocalSandboxSessionState) -> None:
        self.state = state
        self._running = False
        self._pty_lock = asyncio.Lock()
        self._pty_processes = {}
        self._reserved_pty_process_ids = set()
        self._fd_close_tasks = set()
        self._host_environment_allowlist = None
        self._files = _UnixLocalFiles(state.manifest)

    @classmethod
    def from_state(cls, state: UnixLocalSandboxSessionState) -> "UnixLocalSandboxSession":
        return cls(state=state)

    async def _validate_manifest_application(
        self,
        *,
        only_ephemeral: bool = False,
        manifest: Manifest | None = None,
        session_running: bool | None = None,
    ) -> None:
        _ = (only_ephemeral, session_running)
        from .._mount_security import validate_manifest_mount_credential_boundaries

        validate_manifest_mount_credential_boundaries(
            manifest or self.state.manifest,
            provider_backend_id="unix_local",
        )

    async def _prepare_backend_workspace(self) -> None:
        workspace = Path(self.state.manifest.root)
        try:
            await run_blocking_workspace_io(partial(workspace.mkdir, parents=True, exist_ok=True))
        except OSError as e:
            raise WorkspaceStartError(path=workspace, cause=e) from e

    async def _after_start(self) -> None:
        # Mark the session live only after restore/apply completes. A resumed UnixLocal session may
        # recreate an empty workspace after cleanup deleted the previous root, so reporting
        # "running" too early can incorrectly skip snapshot restoration based on a stale
        # fingerprint cache file.
        self._running = True

    async def _after_start_failed(self) -> None:
        self._running = False

    def _wrap_stop_error(self, error: Exception) -> Exception:
        return WorkspaceStopError(path=Path(self.state.manifest.root), cause=error)

    async def _apply_manifest(
        self,
        *,
        only_ephemeral: bool = False,
        provision_accounts: bool = True,
    ) -> MaterializationResult:
        _assert_unix_local_host_path_grants_unsupported(self.state.manifest)
        if self.state.manifest.users or self.state.manifest.groups:
            raise ValueError(
                "UnixLocalSandboxSession does not support manifest users or groups because "
                "provisioning would run on the host machine"
            )
        return await super()._apply_manifest(
            only_ephemeral=only_ephemeral,
            provision_accounts=provision_accounts,
        )

    async def provision_manifest_accounts(self) -> None:
        if self.state.manifest.users or self.state.manifest.groups:
            raise ValueError(
                "UnixLocalSandboxSession does not support manifest users or groups because "
                "provisioning would run on the host machine"
            )

    async def _after_shutdown(self) -> None:
        await self._wait_for_fd_close_tasks()
        # Best-effort: mark session not running. We intentionally do not delete the workspace
        # directory here; cleanup is handled by the Client.delete().
        self._running = False

    async def _after_stop(self) -> None:
        await self._wait_for_fd_close_tasks()

    async def _resolve_exposed_port(self, port: int) -> ExposedPortEndpoint:
        return ExposedPortEndpoint(host="127.0.0.1", port=port, tls=False)

    def supports_pty(self) -> bool:
        return True

    def _prepare_exec_command(
        self,
        *command: str | Path,
        shell: bool | list[str],
        user: str | User | None,
    ) -> list[str]:
        if shell is True:
            shell = ["sh", "-c"]
        return super()._prepare_exec_command(*command, shell=shell, user=user)

    async def _exec_internal(
        self, *command: str | Path, timeout: float | None = None
    ) -> ExecResult:
        env, cwd = await self._resolved_exec_context()
        workspace_root = await asyncio.to_thread(Path(cwd).resolve)
        command_parts = self._workspace_relative_command_parts(command, workspace_root)
        process_cwd, command_parts = self._shell_workspace_process_context(
            command_parts=command_parts,
            workspace_root=workspace_root,
            cwd=cwd,
        )
        exec_command = self._confined_exec_command(
            command_parts=command_parts,
            workspace_root=workspace_root,
            env=env,
        )

        try:
            proc = await asyncio.create_subprocess_exec(
                *exec_command,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=process_cwd,
                env=env,
                start_new_session=True,
            )

            try:
                stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
            except asyncio.TimeoutError as e:
                try:
                    # process tree cleanup
                    os.killpg(proc.pid, signal.SIGKILL)
                except Exception:
                    pass
                raise ExecTimeoutError(command=command, timeout_s=timeout, cause=e) from e
        except ExecTimeoutError:
            raise
        except Exception as e:
            raise ExecTransportError(command=command, cause=e) from e

        return ExecResult(
            stdout=stdout or b"", stderr=stderr or b"", exit_code=proc.returncode or 0
        )

    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:
        _ = timeout
        env, cwd = await self._resolved_exec_context()
        workspace_root = await asyncio.to_thread(Path(cwd).resolve)
        sanitized_command = self._prepare_exec_command(*command, shell=shell, user=user)
        command_parts = self._workspace_relative_command_parts(sanitized_command, workspace_root)
        process_cwd, command_parts = self._shell_workspace_process_context(
            command_parts=command_parts,
            workspace_root=workspace_root,
            cwd=cwd,
        )
        exec_command = self._confined_exec_command(
            command_parts=command_parts,
            workspace_root=workspace_root,
            env=env,
        )

        if tty:
            primary_fd, secondary_fd = os.openpty()

            def _preexec() -> None:
                os.setsid()
                fcntl.ioctl(secondary_fd, termios.TIOCSCTTY, 0)
                # PTY children should use default terminal signal behavior even if the parent
                # process temporarily ignores signals under the test runner.
                _restore_pty_child_signal_defaults()

            try:
                process = await asyncio.create_subprocess_exec(
                    *exec_command,
                    stdin=secondary_fd,
                    stdout=secondary_fd,
                    stderr=secondary_fd,
                    cwd=process_cwd,
                    env=env,
                    preexec_fn=_preexec,
                )
            except BaseException:
                with suppress(OSError):
                    os.close(primary_fd)
                with suppress(OSError):
                    os.close(secondary_fd)
                raise
            else:
                with suppress(OSError):
                    os.close(secondary_fd)
                entry = _UnixPtyProcessEntry(process=process, tty=True, primary_fd=primary_fd)
                entry.pump_tasks = [asyncio.create_task(self._pump_pty_primary_fd(entry))]
        else:
            process = await asyncio.create_subprocess_exec(
                *exec_command,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=process_cwd,
                env=env,
                start_new_session=True,
            )
            entry = _UnixPtyProcessEntry(process=process, tty=False)
            entry.pump_tasks = [
                asyncio.create_task(self._pump_process_stream(entry, process.stdout)),
                asyncio.create_task(self._pump_process_stream(entry, process.stderr)),
            ]

        entry.wait_task = asyncio.create_task(self._watch_process_exit(entry))

        pruned_entry: _UnixPtyProcessEntry | None = None
        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)

        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, output_closed = 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,
            output_closed=output_closed,
        )

    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 or entry.primary_fd is None:
                raise RuntimeError("stdin is not available for this process")
            try:
                os.write(entry.primary_fd, chars.encode("utf-8"))
            except OSError as e:
                if e.errno not in {
                    errno.EIO,
                    errno.EBADF,
                    errno.EPIPE,
                    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, output_closed = 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,
            output_closed=output_closed,
        )

    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)

    async def _resolved_exec_context(self) -> tuple[dict[str, str], str]:
        if self._host_environment_allowlist is None:
            env = dict(os.environ)
        else:
            env = {
                name: value
                for name, value in os.environ.items()
                if name in self._host_environment_allowlist
            }
        env.update(await self.state.manifest.environment.resolve())

        workspace = Path(self.state.manifest.root)
        if not await asyncio.to_thread(workspace.exists):
            raise WorkspaceRootNotFoundError(path=workspace)

        env["HOME"] = str(workspace)
        return env, str(workspace)

    async def _pump_process_stream(
        self,
        entry: _UnixPtyProcessEntry,
        stream: asyncio.StreamReader | None,
    ) -> None:
        if stream is None:
            return

        while True:
            chunk = await stream.read(_PTY_READ_CHUNK_BYTES)
            if chunk == b"":
                break
            async with entry.output_lock:
                entry.output_chunks.append(chunk)
            entry.output_notify.set()

    async def _watch_process_exit(self, entry: _UnixPtyProcessEntry) -> None:
        await entry.process.wait()
        if entry.pump_tasks:
            await asyncio.gather(*entry.pump_tasks, return_exceptions=True)
        entry.output_closed.set()
        entry.output_notify.set()

    async def _pump_pty_primary_fd(self, entry: _UnixPtyProcessEntry) -> None:
        primary_fd = entry.primary_fd
        if primary_fd is None:
            return

        loop = asyncio.get_running_loop()
        while True:
            try:
                chunk = await loop.run_in_executor(None, os.read, primary_fd, _PTY_READ_CHUNK_BYTES)
            except OSError as e:
                if e.errno in {errno.EIO, errno.EBADF}:
                    break
                raise

            if chunk == b"":
                break
            async with entry.output_lock:
                entry.output_chunks.append(chunk)
            entry.output_notify.set()

    async def _collect_pty_output(
        self,
        *,
        entry: _UnixPtyProcessEntry,
        yield_time_ms: int,
        max_output_tokens: int | None,
    ) -> tuple[bytes, int | None, bool]:
        return await collect_pty_output(
            output_chunks=entry.output_chunks,
            output_lock=entry.output_lock,
            output_notify=entry.output_notify,
            is_done=entry.output_closed.is_set,
            yield_time_ms=yield_time_ms,
            max_output_tokens=max_output_tokens,
        )

    async def _finalize_pty_update(
        self,
        *,
        process_id: int,
        entry: _UnixPtyProcessEntry,
        output: bytes,
        original_token_count: int | None,
        output_closed: bool,
    ) -> PtyExecUpdate:
        exit_code: int | None = entry.process.returncode if output_closed else None
        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) -> _UnixPtyProcessEntry | None:
        if len(self._pty_processes) < PTY_PROCESSES_MAX:
            return None

        meta = [
            (process_id, entry.last_used, entry.output_closed.is_set())
            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: _UnixPtyProcessEntry) -> None:
        process = entry.process
        primary_fd = entry.primary_fd
        entry.primary_fd = None

        if process.returncode is None and process.pid is not None:
            with suppress(ProcessLookupError):
                os.killpg(process.pid, signal.SIGKILL)

        for task in entry.pump_tasks:
            task.cancel()
        if entry.wait_task is not None:
            entry.wait_task.cancel()
        if entry.tty:
            if primary_fd is not None:
                # On macOS we have observed os.close() on the PTY master fd block while a
                # background reader thread is still inside os.read(). Keep the close task owned
                # by the session without making PTY termination wait indefinitely for it.
                self._schedule_fd_close(primary_fd)
            entry.output_closed.set()
            entry.output_notify.set()
            return

        if primary_fd is not None:
            _close_fd_quietly(primary_fd)
        await asyncio.gather(*entry.pump_tasks, return_exceptions=True)
        if entry.wait_task is not None:
            await asyncio.gather(entry.wait_task, return_exceptions=True)

    def _schedule_fd_close(self, fd: int) -> None:
        task = asyncio.create_task(asyncio.to_thread(_close_fd_quietly, fd))
        self._fd_close_tasks.add(task)
        task.add_done_callback(self._fd_close_tasks.discard)

    async def _wait_for_fd_close_tasks(self) -> None:
        tasks = tuple(self._fd_close_tasks)
        if tasks:
            await asyncio.wait(tasks, timeout=_PTY_FD_CLOSE_GRACE_SECONDS)

    def _confined_exec_command(
        self,
        *,
        command_parts: list[str],
        workspace_root: Path,
        env: Mapping[str, str],
    ) -> list[str]:
        if sys.platform != "darwin":
            return command_parts

        sandbox_exec = shutil.which("sandbox-exec")
        if not sandbox_exec:
            raise ExecTransportError(
                command=command_parts,
                context={
                    "reason": "unix_local_confinement_unavailable",
                    "platform": sys.platform,
                    "workspace_root": str(workspace_root),
                },
            )

        profile = self._darwin_exec_profile(
            workspace_root,
            extra_read_paths=self._darwin_additional_read_paths(
                command_parts=command_parts,
                env=env,
            ),
            extra_path_grants=self._darwin_extra_path_grant_roots(),
        )
        return [sandbox_exec, "-p", profile, *command_parts]

    @staticmethod
    def _workspace_relative_command_parts(
        command: Sequence[str | Path],
        workspace_root: Path,
    ) -> list[str]:
        command_parts = [str(part) for part in command]
        rewritten = [command_parts[0]]
        for part in command_parts[1:]:
            path_part = Path(part)
            if not path_part.is_absolute():
                rewritten.append(part)
                continue
            try:
                relative = path_part.relative_to(workspace_root)
            except ValueError:
                rewritten.append(part)
                continue
            rewritten.append("." if not relative.parts else relative.as_posix())
        return rewritten

    @staticmethod
    def _darwin_allowable_read_roots(
        path: Path,
        *,
        host_home: Path,
        allow_virtual_environment_root: bool = False,
    ) -> list[Path]:
        candidates: set[Path] = set()
        normalized = path.expanduser()
        try:
            resolved = normalized.resolve(strict=False)
        except OSError:
            resolved = normalized

        if normalized.is_dir():
            candidates.add(normalized)
        else:
            candidates.add(normalized.parent)

        if resolved.is_dir():
            candidates.add(resolved)
        else:
            candidates.add(resolved.parent)

        if allow_virtual_environment_root:
            for candidate in (normalized, resolved):
                if candidate.name != "bin":
                    continue
                virtual_env_root = candidate.parent
                if (virtual_env_root / "pyvenv.cfg").is_file():
                    candidates.add(virtual_env_root)

        resolved_text = resolved.as_posix()
        if resolved_text == "/opt/homebrew" or resolved_text.startswith("/opt/homebrew/"):
            candidates.add(Path("/opt/homebrew"))
        if resolved_text == "/usr/local" or resolved_text.startswith("/usr/local/"):
            candidates.add(Path("/usr/local"))
        if resolved_text == "/Library/Frameworks" or resolved_text.startswith(
            "/Library/Frameworks/"
        ):
            candidates.add(Path("/Library/Frameworks"))

        try:
            relative_to_home = resolved.relative_to(host_home)
        except ValueError:
            relative_to_home = None
        if relative_to_home is not None and relative_to_home.parts:
            first_segment = relative_to_home.parts[0]
            if first_segment.startswith("."):
                candidates.add(host_home / first_segment)
            elif len(relative_to_home.parts) >= 2 and relative_to_home.parts[:2] == (
                "Library",
                "Python",
            ):
                candidates.add(host_home / "Library" / "Python")

        return sorted(
            candidates, key=lambda candidate: (len(candidate.parts), candidate.as_posix())
        )

    def _darwin_additional_read_paths(
        self,
        *,
        command_parts: list[str],
        env: Mapping[str, str],
    ) -> list[Path]:
        host_home = Path.home().resolve()
        allowed: list[Path] = []
        seen: set[str] = set()

        def _append(
            path: str | Path | None,
            *,
            allow_virtual_environment_root: bool = False,
        ) -> None:
            if path is None:
                return
            candidate = Path(path).expanduser()
            if not candidate.is_absolute():
                return
            for root in self._darwin_allowable_read_roots(
                candidate,
                host_home=host_home,
                allow_virtual_environment_root=allow_virtual_environment_root,
            ):
                key = root.as_posix()
                if key in seen:
                    continue
                seen.add(key)
                allowed.append(root)

        child_path_entries = env.get("PATH", "").split(os.pathsep)
        for path_entry in child_path_entries:
            if path_entry:
                _append(path_entry)

        executable = shutil.which(command_parts[0], path=env.get("PATH"))
        _append(executable)

        # The client must permit PATH inheritance before retained host entries can widen a bin
        # grant to its virtual environment root. Matching manifest values cannot grant authority.
        if self._host_environment_allowlist is None or "PATH" in self._host_environment_allowlist:
            for path_entry in os.environ.get("PATH", "").split(os.pathsep):
                if path_entry and path_entry in child_path_entries:
                    _append(path_entry, allow_virtual_environment_root=True)
        return allowed

    def _darwin_extra_path_grant_roots(self) -> list[tuple[Path, bool]]:
        roots: list[tuple[Path, bool]] = []
        seen: set[tuple[str, bool]] = set()

        def _append(path: Path, *, read_only: bool) -> None:
            _raise_if_filesystem_root(path, resolved=True)
            key = (path.as_posix(), read_only)
            if key in seen:
                return
            seen.add(key)
            roots.append((path, read_only))

        for grant in self.state.manifest.extra_path_grants:
            grant_path = Path(grant.path).expanduser()
            try:
                resolved = grant_path.resolve(strict=False)
            except OSError:
                _append(grant_path, read_only=grant.read_only)
                continue
            _raise_if_filesystem_root(resolved, resolved=True)
            _append(grant_path, read_only=grant.read_only)
            if resolved != grant_path:
                _append(resolved, read_only=grant.read_only)

        return roots

    def _darwin_exec_profile(
        self,
        workspace_root: Path,
        *,
        extra_read_paths: Sequence[Path] = (),
        extra_path_grants: Sequence[tuple[Path, bool]] = (),
    ) -> str:
        def _literal(path: Path | str) -> str:
            escaped = str(path).replace("\\", "\\\\").replace('"', '\\"')
            return f'"{escaped}"'

        denied_paths = [
            Path("/Users"),
            Path("/Volumes"),
            Path("/Applications"),
            Path("/Library"),
            Path("/opt"),
            Path("/etc"),
            Path("/private/etc"),
            Path("/tmp"),
            Path("/private/tmp"),
            Path("/private"),
            Path("/var"),
            Path("/usr"),
        ]
        allow_rules = [
            f"(allow file-read-data file-read-metadata (subpath {_literal(workspace_root)}))",
            f"(allow file-write* (subpath {_literal(workspace_root)}))",
            *[
                f"(allow file-read-data file-read-metadata (subpath {_literal(path)}))"
                for path in extra_read_paths
            ],
            *[
                f"(allow file-read-data file-read-metadata (subpath {_literal(path)}))"
                for path, _read_only in extra_path_grants
            ],
            *[
                f"(allow file-write* (subpath {_literal(path)}))"
                for path, read_only in extra_path_grants
                if not read_only
            ],
            *[
                f"(deny file-write* (subpath {_literal(path)}))"
                for path, read_only in extra_path_grants
                if read_only
            ],
            '(allow file-read-data file-read-metadata (subpath "/usr/bin"))',
            '(allow file-read-data file-read-metadata (subpath "/usr/lib"))',
            '(allow file-read-data file-read-metadata (subpath "/bin"))',
            '(allow file-read-data file-read-metadata (subpath "/System"))',
            '(allow file-read-data file-read-metadata (literal "/private/var/select/sh"))',
            '(allow file-write* (literal "/dev/null"))',
        ]
        deny_rules = "\n".join(
            f"(deny file-read-data (subpath {_literal(path)}))\n"
            f"(deny file-write* (subpath {_literal(path)}))"
            for path in denied_paths
        )
        return "\n".join(
            [
                "(version 1)",
                "(allow default)",
                deny_rules,
                *allow_rules,
            ]
        )

    @staticmethod
    def _shell_workspace_process_context(
        *,
        command_parts: list[str],
        workspace_root: Path,
        cwd: str,
    ) -> tuple[str, list[str]]:
        if len(command_parts) < 3 or command_parts[0] != "sh" or command_parts[1] != "-c":
            return cwd, command_parts

        workspace_cd = f"cd {shlex.quote(str(workspace_root))} && {command_parts[2]}"
        rewritten = [*command_parts]
        rewritten[2] = workspace_cd
        return "/", rewritten

    def normalize_path(self, path: Path | str, *, for_write: bool = False) -> Path:
        self._files.configure(self.state.manifest)
        policy = self._workspace_path_policy()
        return policy.normalize_path(path, for_write=for_write, resolve_symlinks=True)

    async def ls(
        self,
        path: Path | str,
        *,
        user: str | User | None = None,
    ) -> list[FileEntry]:
        normalized = self.normalize_path(path)
        if user is not None:
            command = ("ls", "-la", "--", str(normalized))
            try:
                result = await self._run_file_operation_as_user("ls", normalized, user=user)
            except OSError as e:
                raise ExecNonZeroError(
                    ExecResult(stdout=b"", stderr=str(e).encode("utf-8"), exit_code=1),
                    command=command,
                    cause=e,
                ) from e
            if result.returncode:
                raise ExecNonZeroError(
                    ExecResult(
                        stdout=result.stdout, stderr=result.stderr, exit_code=result.returncode
                    ),
                    command=command,
                )
            return [
                FileEntry(
                    path=entry["path"],
                    permissions=Permissions.from_mode(entry["mode"]).model_copy(
                        update={"directory": entry["kind"] == "directory"}
                    ),
                    owner=entry["owner"],
                    group=entry["group"],
                    size=entry["size"],
                    kind=EntryKind(entry["kind"]),
                )
                for entry in json.loads(result.stdout)
            ]

        command = ("ls", "-la", "--", str(normalized))
        try:
            with (
                self._files.directory(normalized) as directory_fd,
                os.scandir(directory_fd) as entries,
            ):
                listed: list[FileEntry] = []
                for entry in entries:
                    stat_result = entry.stat(follow_symlinks=False)
                    if entry.is_symlink():
                        kind = EntryKind.SYMLINK
                    elif entry.is_dir(follow_symlinks=False):
                        kind = EntryKind.DIRECTORY
                    elif entry.is_file(follow_symlinks=False):
                        kind = EntryKind.FILE
                    else:
                        kind = EntryKind.OTHER
                    listed.append(
                        FileEntry(
                            path=str(normalized / entry.name),
                            permissions=Permissions.from_mode(stat_result.st_mode),
                            owner=str(stat_result.st_uid),
                            group=str(stat_result.st_gid),
                            size=stat_result.st_size,
                            kind=kind,
                        )
                    )
                return listed
        except OSError as e:
            raise ExecNonZeroError(
                ExecResult(stdout=b"", stderr=str(e).encode("utf-8"), exit_code=1),
                command=command,
                cause=e,
            ) from e

    async def mkdir(
        self,
        path: Path | str,
        *,
        parents: bool = False,
        user: str | User | None = None,
    ) -> None:
        if user is not None:
            normalized = await self._check_mkdir_with_exec(path, parents=parents, user=user)
        else:
            normalized = self.normalize_path(path, for_write=True)
        try:
            self._files.mkdir(normalized, parents=parents)
        except OSError as e:
            raise WorkspaceArchiveWriteError(path=normalized, cause=e) from e

    async def rm(
        self,
        path: Path | str,
        *,
        recursive: bool = False,
        user: str | User | None = None,
    ) -> None:
        if user is not None:
            normalized = await self._check_rm_with_exec(path, recursive=recursive, user=user)
        else:
            normalized = self.normalize_path(path, for_write=True)
        try:
            if recursive:
                await run_blocking_workspace_io(partial(self._files.rm, normalized, recursive=True))
            else:
                self._files.rm(normalized, recursive=False)
        except FileNotFoundError as e:
            if recursive:
                return
            raise ExecNonZeroError(
                ExecResult(stdout=b"", stderr=str(e).encode("utf-8"), exit_code=1),
                command=("rm", "-rf" if recursive else "--", str(normalized)),
                cause=e,
            ) from e
        except OSError as e:
            raise WorkspaceArchiveWriteError(path=normalized, cause=e) from e

    async def _remove_workspace_entry_on_resume(self, path: Path) -> None:
        # Snapshot cleanup owns the entry, not the target of a stale symlink.
        target = self.normalize_path(path.parent, for_write=True) / path.name
        try:
            await run_blocking_workspace_io(partial(self._files.rm, target, recursive=True))
        except FileNotFoundError:
            return
        except OSError as e:
            raise WorkspaceArchiveWriteError(path=target, cause=e) from e

    async def _read_bounded(self, path: Path, *, max_bytes: int) -> bytes:
        return self._files.read_bounded(self.normalize_path(path), max_bytes)

    async def read(self, path: Path, *, user: str | User | None = None) -> io.IOBase:
        if user is not None:
            await self._check_read_with_exec(path, user=user)

        workspace_path = self.normalize_path(path)
        try:
            return self._files.read(workspace_path)
        except FileNotFoundError as e:
            raise WorkspaceReadNotFoundError(path=path, cause=e) from e
        except OSError as e:
            raise WorkspaceArchiveReadError(path=path, cause=e) from e

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

        workspace_path = self.normalize_path(path, for_write=True)
        if user is not None:
            await self._write_stream_with_exec(workspace_path, payload.stream, user=user)
            return

        try:
            self._files.write(workspace_path, payload.stream)
        except OSError as e:
            raise WorkspaceArchiveWriteError(path=workspace_path, cause=e) from e

    async def mv(
        self,
        source: Path | str,
        destination: Path | str,
        *,
        user: str | User | None = None,
    ) -> None:
        # A rename of the entry, descriptor-relative like every other file operation here,
        # so the paths validated above are the ones acted on. `os.rename` never puts the
        # source inside an existing directory the way `mv` does; it fails instead.
        normalized_source = self._normalize_entry_path(source, for_write=True)
        normalized_destination = self._normalize_entry_path(destination, for_write=True)
        command = ("mv", "-f", "--", str(normalized_source), str(normalized_destination))
        if user is not None:
            try:
                result = await self._run_file_operation_as_user(
                    "rename", normalized_source, normalized_destination, user=user
                )
            except OSError as e:
                raise ExecNonZeroError(
                    ExecResult(stdout=b"", stderr=str(e).encode("utf-8"), exit_code=1),
                    command=command,
                    cause=e,
                ) from e
            if result.returncode:
                raise ExecNonZeroError(
                    ExecResult(
                        stdout=result.stdout, stderr=result.stderr, exit_code=result.returncode
                    ),
                    command=command,
                )
            return
        try:
            self._files.rename(normalized_source, normalized_destination)
        except OSError as e:
            raise ExecNonZeroError(
                ExecResult(stdout=b"", stderr=str(e).encode("utf-8"), exit_code=1),
                command=command,
                cause=e,
            ) from e

    async def same_file(
        self,
        left: Path | str,
        right: Path | str,
        *,
        follow_symlinks: bool = True,
        user: str | User | None = None,
    ) -> bool:
        normalize = self.normalize_path if follow_symlinks else self._normalize_entry_path
        normalized_left = normalize(left)
        normalized_right = normalize(right)
        command = ("test", str(normalized_left), "-ef", str(normalized_right))
        if user is not None:
            try:
                result = await self._run_file_operation_as_user(
                    "same_file",
                    normalized_left,
                    normalized_right,
                    user=user,
                    payload=b"1" if follow_symlinks else b"0",
                )
            except OSError as e:
                raise ExecNonZeroError(
                    ExecResult(stdout=b"", stderr=str(e).encode("utf-8"), exit_code=1),
                    command=command,
                    cause=e,
                ) from e
            if result.returncode:
                raise ExecNonZeroError(
                    ExecResult(
                        stdout=result.stdout, stderr=result.stderr, exit_code=result.returncode
                    ),
                    command=command,
                )
            return bool(json.loads(result.stdout))
        try:
            return self._files.same_file(
                normalized_left, normalized_right, follow_symlinks=follow_symlinks
            )
        except OSError as e:
            raise ExecNonZeroError(
                ExecResult(stdout=b"", stderr=str(e).encode("utf-8"), exit_code=1),
                command=command,
                cause=e,
            ) from e

    def _normalize_entry_path(self, path: Path | str, *, for_write: bool = False) -> Path:
        # Resolve and authorize the parent without following the leaf that rename/stat owns.
        self._files.configure(self.state.manifest)
        lexical = Path(path)
        if not lexical.is_absolute():
            lexical = self._workspace_path_policy().absolute_workspace_path(path)
        resolved = lexical.parent.resolve(strict=False) / lexical.name
        return self._files.authorize(resolved, for_write=for_write)

    async def _write_new_file(
        self,
        path: Path,
        data: io.IOBase,
        *,
        user: str | User | None = None,
    ) -> None:
        payload = coerce_write_payload(path=path, data=data)
        # Resolve the parent the way the ordinary write path does, so a supported internal
        # symlink such as "internal -> real" still works, then keep the leaf name
        # unresolved so the file ops open it with O_NOFOLLOW and a symlink at the target
        # name is rejected rather than followed.
        requested = Path(path)
        target = self.normalize_path(requested.parent, for_write=True) / requested.name
        if user is not None:
            await self._write_new_stream_with_exec(target, payload.stream, user=user)
            return

        try:
            self._files.write_new(target, payload.stream)
        except _unix_local_file_ops._IncompleteCreateError as e:
            raise WorkspaceArchiveWriteError(
                path=target,
                cause=e,
                retryable=False,
                message=_INCOMPLETE_CREATE_MESSAGE,
            ) from e
        except FileExistsError:
            raise
        except OSError as e:
            raise WorkspaceArchiveWriteError(path=target, cause=e) from e

    async def _write_new_stream_with_exec(
        self,
        path: Path,
        stream: io.IOBase,
        *,
        user: str | User,
    ) -> None:
        payload = stream.read()
        if isinstance(payload, str):
            payload = payload.encode("utf-8")
        elif not isinstance(payload, bytes):
            payload = bytes(payload)
        try:
            result = await self._run_file_operation_as_user(
                "write_new", path, user=user, payload=payload
            )
        except OSError as e:
            raise WorkspaceArchiveWriteError(path=path, cause=e) from e
        if result.returncode == _unix_local_file_ops._EXISTING_TARGET_EXIT_CODE:
            raise FileExistsError(str(path))
        if result.returncode == _unix_local_file_ops._INCOMPLETE_CREATE_EXIT_CODE:
            raise WorkspaceArchiveWriteError(
                path=path,
                retryable=False,
                message=_INCOMPLETE_CREATE_MESSAGE,
            )
        if result.returncode:
            raise WorkspaceArchiveWriteError(
                path=path,
                context={
                    "stderr": result.stderr.decode("utf-8", errors="replace"),
                    "operation": "write_new",
                },
            )

    async def _write_stream_with_exec(
        self,
        path: Path,
        stream: io.IOBase,
        *,
        user: str | User,
    ) -> None:
        payload = stream.read()
        if isinstance(payload, str):
            payload = payload.encode("utf-8")
        elif not isinstance(payload, bytes):
            payload = bytes(payload)
        try:
            result = await self._run_file_operation_as_user(
                "write", path, user=user, payload=payload
            )
        except OSError as e:
            raise WorkspaceArchiveWriteError(path=path, cause=e) from e
        if result.returncode:
            raise WorkspaceArchiveWriteError(
                path=path,
                context={
                    "stderr": result.stderr.decode("utf-8", errors="replace"),
                    "operation": "write",
                },
            )

    async def _run_file_operation_as_user(
        self,
        operation: Literal["ls", "write", "write_new", "rename", "same_file"],
        path: Path,
        *more_paths: Path,
        user: str | User,
        payload: bytes = b"",
    ) -> subprocess.CompletedProcess[bytes]:
        # Authorization is synchronous and captured for this operation before dispatch.
        for_write = operation in ("write", "write_new", "rename")
        paths = [self._files.authorize(each, for_write=for_write) for each in (path, *more_paths)]
        command = self._prepare_exec_command(
            "python3",
            "-I",
            "-S",
            "-c",
            _USER_FILE_WORKER_SOURCE,
            operation,
            *(str(each) for each in paths),
            shell=False,
            user=user,
        )
        # Resolve sudo from trusted host configuration, never the workspace's command environment.
        executable = shutil.which(command[0])
        if executable is None:
            raise FileNotFoundError(f"UnixLocal user dispatcher is unavailable: {command[0]}")
        command[0] = executable

        # This trusted worker enforces the file boundary itself, like direct host file I/O.
        # It does not execute workspace commands or load workspace Python modules.
        def run_worker() -> subprocess.CompletedProcess[bytes]:
            return subprocess.run(
                command,
                input=payload,
                capture_output=True,
                cwd="/",
                env={"PATH": os.defpath},
                start_new_session=True,
                check=False,
            )

        return await run_blocking_workspace_io(run_worker)

    async def running(self) -> bool:
        return self._running

    async def persist_workspace(self) -> io.IOBase:
        root = Path(self.state.manifest.root)
        if not await asyncio.to_thread(root.exists):
            raise WorkspaceArchiveReadError(
                path=root, context={"reason": "workspace_root_not_found"}
            )

        skip = self._persist_workspace_skip_relpaths()
        buf = io.BytesIO()

        def _archive_workspace() -> None:
            roots = (root, root.resolve(strict=False))
            symlinks: list[tarfile.TarInfo] = []
            with tarfile.open(fileobj=buf, mode="w") as tar:

                def filter_member(member: tarfile.TarInfo) -> tarfile.TarInfo | None:
                    # tarfile records inodes before filtering. Clear even excluded entries so
                    # every retained hardlink has its own payload. Unlike dereference=True,
                    # this preserves symlinks instead of reading their targets on the host.
                    getattr(tar, "inodes").clear()  # noqa: B009 - Not exposed by typeshed.
                    if should_skip_tar_member(member.name, skip_rel_paths=skip, root_name=None):
                        return None
                    if member.isfifo() or member.ischr() or member.isblk():
                        return None
                    if member.issym():
                        symlinks.append(member)
                        return None
                    return member

                tar.add(root, arcname=".", filter=filter_member)
                # Defer symlink headers until capture is complete. The live tree can change
                # during tar.add, so only the captured topology can prove containment.
                members = {
                    PurePosixPath(member.name).as_posix(): member
                    for member in [*tar.getmembers(), *symlinks]
                }
                for member in symlinks:
                    # Keep the proof graph unchanged: a hop through an originally absolute
                    # target must stay unprovable regardless of symlink emission order.
                    archived_member = copy.copy(member)
                    if member.linkname.startswith("/"):
                        rebased = _rebase_symlink_target(
                            member.linkname, link_name=member.name, roots=roots
                        )
                        if rebased != member.linkname and _symlink_target_stays_under(
                            members, link_name=member.name, target=rebased
                        ):
                            archived_member.linkname = rebased
                    tar.addfile(archived_member)

        try:
            await run_blocking_workspace_io(_archive_workspace)
        except (tarfile.TarError, OSError) as e:
            raise WorkspaceArchiveReadError(path=root, cause=e) from e

        buf.seek(0)
        return buf

    async def _restore_snapshot_into_workspace_on_resume(self) -> None:
        root = Path(self.state.manifest.root)
        archive = await self.state.snapshot.restore(dependencies=self.dependencies)

        def validate_archive() -> None:
            try:
                with tarfile.open(fileobj=archive, mode="r:*") as tar:
                    validate_tarfile(tar, allow_external_symlink_targets=False)
                archive.seek(0)
            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

        try:
            # Older snapshots may contain unsupported members. Reject them before discarding
            # the live files; keep hydrate_workspace's own validation for direct callers too.
            await run_blocking_workspace_io(validate_archive)
            await self._clear_workspace_root_on_resume()
            await self.hydrate_workspace(archive)
        finally:
            with suppress(Exception):
                archive.close()

    async def hydrate_workspace(self, data: io.IOBase) -> None:
        root = Path(self.state.manifest.root)

        def _extract_workspace() -> None:
            root.mkdir(parents=True, exist_ok=True)
            with tarfile.open(fileobj=data, mode="r:*") as tar:
                safe_extract_tarfile(
                    tar,
                    root=root,
                    allow_external_symlink_targets=False,
                )

        try:
            await run_blocking_workspace_io(_extract_workspace)
        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

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
@redact_mount_error_data
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.
    """
    validate_manifest_mount_credential_boundaries(
        self.state.manifest,
        provider_backend_id=self.state.type,
    )
    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()

supports_docker_volume_mounts

supports_docker_volume_mounts() -> bool

Return whether this backend attaches Docker volume mounts before manifest apply.

Source code in src/agents/sandbox/session/base_sandbox_session.py
def supports_docker_volume_mounts(self) -> bool:
    """Return whether this backend attaches Docker volume mounts before manifest apply."""

    return False

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
@redact_mount_error_data
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
@redact_mount_error_data
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.
    """

    lock = self._aclose_lock
    if lock is None:
        lock = asyncio.Lock()
        self._aclose_lock = lock
    async with lock:
        await self._aclose_impl()

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
@redact_mount_error_data
async def run_pre_stop_hooks(self) -> None:
    """Run registered pre-stop hooks once before workspace persistence."""

    lock = self._pre_stop_hooks_lock
    if lock is None:
        lock = asyncio.Lock()
        self._pre_stop_hooks_lock = lock
    async with lock:
        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:
            self._pre_stop_hooks_failed = True
            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

exec async

exec(
    *command: str | Path,
    timeout: float | None = None,
    shell: bool | list[str] = True,
    user: str | User | None = None,
) -> ExecResult

Execute a command inside the session.

:param command: Command and args (will be stringified). :param timeout: Optional wall-clock timeout in seconds. :param shell: Whether to run this command in a shell. If True is provided, the command will be run prefixed by sh -lc. A custom shell prefix may be used by providing a list.

:returns: An ExecResult containing stdout/stderr and exit code.

:raises TimeoutError: If the sandbox cannot complete within timeout.

Source code in src/agents/sandbox/session/base_sandbox_session.py
@redact_mount_error_data
async def exec(
    self,
    *command: str | Path,
    timeout: float | None = None,
    shell: bool | list[str] = True,
    user: str | User | None = None,
) -> ExecResult:
    """Execute a command inside the session.

    :param command: Command and args (will be stringified).
    :param timeout: Optional wall-clock timeout in seconds.
    :param shell: Whether to run this command in a shell. If ``True`` is provided,
        the command will be run prefixed by ``sh -lc``. A custom shell prefix may be used
        by providing a list.

    :returns: An ``ExecResult`` containing stdout/stderr and exit code.

    :raises TimeoutError: If the sandbox cannot complete within `timeout`.
    """

    sanitized_command = self._prepare_exec_command(*command, shell=shell, user=user)
    return await self._exec_internal(*sanitized_command, timeout=timeout)

read_bounded async

read_bounded(path: Path, *, max_bytes: int) -> bytes

Read a prefix of at most max_bytes bytes.

Uses the session identity and the same path scope as read(path). A result of exactly max_bytes bytes does not indicate EOF. Backends provided by the SDK bound acquisition from the source. For compatibility, custom backends inherit a fallback that consumes and closes the stream returned by read(). That fallback cannot bound any data acquired inside read() before it returns. Override _read_bounded to provide that guarantee. Encoded transports may reject responses exceeding their bounded framing budget. Failures use payload-free WorkspaceArchiveReadError diagnostics.

Source code in src/agents/sandbox/session/base_sandbox_session.py
async def read_bounded(self, path: Path, *, max_bytes: int) -> bytes:
    """Read a prefix of at most ``max_bytes`` bytes.

    Uses the session identity and the same path scope as ``read(path)``.
    A result of exactly ``max_bytes`` bytes does not indicate EOF. Backends
    provided by the SDK bound acquisition from the source. For compatibility,
    custom backends inherit a fallback that consumes and closes the stream
    returned by ``read()``. That fallback cannot bound any data acquired inside
    ``read()`` before it returns. Override ``_read_bounded`` to provide that
    guarantee. Encoded transports may reject responses exceeding their bounded
    framing budget. Failures use payload-free ``WorkspaceArchiveReadError``
    diagnostics.
    """
    if max_bytes <= 0:
        raise ValueError("max_bytes must be positive")
    # Raise outside the handler: provider exceptions may retain response bodies.
    reason = "bounded_read_failed"
    retryable: bool | None = None
    missing = False
    try:
        return await self._read_bounded(path, max_bytes=max_bytes)
    except (FileNotFoundError, WorkspaceReadNotFoundError):
        missing = True
    except SandboxError as error:
        retryable = error.retryable
        if error.context.get("reason") == "bounded_read_wire_limit":
            reason = "bounded_read_wire_limit"
    except Exception:
        # Discard payload-bearing provider diagnostics at this boundary.
        reason = "bounded_read_failed"
    if missing:
        raise WorkspaceReadNotFoundError(path=path)
    raise WorkspaceArchiveReadError(path=path, context={"reason": reason}, retryable=retryable)

extract async

extract(
    path: Path | str,
    data: IOBase,
    *,
    compression_scheme: Literal["tar", "zip"] | None = None,
    archive_limits: SandboxArchiveLimits | 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. :param archive_limits: optional per-call archive resource limits. If omitted, the session default is used.

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,
    archive_limits: SandboxArchiveLimits | 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.
    :param archive_limits: optional per-call archive resource limits. If omitted,
        the session default is used.
    """
    if archive_limits is not None:
        archive_limits.validate()
    effective_archive_limits = (
        archive_limits if archive_limits is not None else self._archive_limits
    )

    await archive_ops.extract_archive(
        self,
        path,
        data,
        compression_scheme=compression_scheme,
        archive_limits=effective_archive_limits,
    )

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()

UnixLocalSandboxSessionState

Bases: SandboxSessionState

Source code in src/agents/sandbox/sandboxes/unix_local.py
class UnixLocalSandboxSessionState(SandboxSessionState):
    type: Literal["unix_local"] = "unix_local"
    workspace_root_owned: bool = False

mount_authority_rebound property

mount_authority_rebound: bool

Whether persisted mount topology was rebound from current trusted configuration.

__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):
        from ...exceptions import (
            _raise_data_redacted_error,
            _replace_data_redacted_process_control_error,
        )
        from .._mount_security import (
            _redact_mount_state_validation_error,
            sanitize_raw_session_state_mount_authority,
        )

        safe_error: BaseException | None = None
        sanitized: object = None
        state_type: object = None
        subclass: SessionStateClass | None = None
        try:
            sanitized, _redacted = sanitize_raw_session_state_mount_authority(payload)
            if not isinstance(sanitized, dict):
                raise ValueError("sandbox session state payload has an invalid shape")
            payload = sanitized
            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("unknown sandbox session state type")

            return cls._mark_persisted_path_grants(
                subclass.model_validate(payload),
                payload=payload,
            )
        except BaseException as error:
            payload.clear()
            if isinstance(sanitized, dict):
                sanitized.clear()
            safe_error = _replace_data_redacted_process_control_error(error)
            if safe_error is None:
                safe_error = _redact_mount_state_validation_error(
                    error,
                    message="sandbox session state payload is invalid",
                )

        payload = cast(Any, None)
        sanitized = None
        state_type = None
        subclass = None
        assert safe_error is not None
        _raise_data_redacted_error(safe_error)

    payload = cast(Any, None)
    raise TypeError("session state payload must be a SandboxSessionState or dict")

model_validate_json classmethod

model_validate_json(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: Literal["allow", "ignore", "forbid"]
    | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self

Validate JSON without retaining malformed input in a public error.

Source code in src/agents/sandbox/session/sandbox_session_state.py
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: Literal["allow", "ignore", "forbid"] | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate JSON without retaining malformed input in a public error."""

    from ...exceptions import (
        _raise_data_redacted_error,
        _replace_data_redacted_process_control_error,
    )
    from .._mount_security import _redact_mount_state_validation_error

    decoded: object = None
    safe_error: BaseException | None = None
    try:
        decoded = json.loads(json_data)
    except BaseException as error:
        safe_error = _replace_data_redacted_process_control_error(error)
        if safe_error is None:
            safe_error = _redact_mount_state_validation_error(
                error,
                message="sandbox session state JSON is invalid",
            )

    if safe_error is not None:
        if isinstance(decoded, dict | list):
            decoded.clear()
        decoded = None
        json_data = cast(Any, None)
        _raise_data_redacted_error(safe_error)

    decoded = None
    try:
        return super().model_validate_json(
            json_data,
            strict=strict,
            extra=extra,
            context=context,
            by_alias=by_alias,
            by_name=by_name,
        )
    except BaseException as error:
        safe_error = _replace_data_redacted_process_control_error(error)
        json_data = cast(Any, None)
        if safe_error is not None:
            _raise_data_redacted_error(safe_error)
        if isinstance(error, Exception):
            raise
        safe_error = _redact_mount_state_validation_error(
            error,
            message="sandbox session state JSON is invalid",
        )
        _raise_data_redacted_error(safe_error)

rebind_persisted_path_grants

rebind_persisted_path_grants(
    trusted_manifest: Manifest | None,
) -> SandboxSessionState

Replace persisted path grants with grants from current trusted configuration.

Source code in src/agents/sandbox/session/sandbox_session_state.py
def rebind_persisted_path_grants(
    self,
    trusted_manifest: Manifest | None,
) -> SandboxSessionState:
    """Replace persisted path grants with grants from current trusted configuration."""

    if not self.path_grants_require_rebind:
        return self
    if trusted_manifest is None:
        raise ValueError(
            "Sandbox session state contains path grants that require a current trusted "
            "manifest before resume"
        )

    trusted_host_path_grant_paths = {
        grant.path
        for grant in trusted_manifest.extra_path_grants
        if grant.host_path is not None
    }
    missing_host_paths = [
        path
        for path in self.path_grants_require_rebind
        if path not in trusted_host_path_grant_paths
    ]
    if missing_host_paths:
        raise ValueError(
            "Sandbox session state requires current trusted host_path values for these "
            f"path grants: {', '.join(missing_host_paths)}"
        )

    rebound_manifest = self.manifest.model_copy(
        update={
            "extra_path_grants": tuple(
                grant.model_copy() for grant in trusted_manifest.extra_path_grants
            )
        },
    )
    rebound = self.model_copy(update={"manifest": rebound_manifest})
    rebound._path_grants_require_rebind = ()
    return rebound

rebind_persisted_mount_authority

rebind_persisted_mount_authority(
    trusted_manifest: Manifest | None,
    *,
    provider_backend_id: str,
) -> SandboxSessionState

Restore redacted mount authority from an exact current trusted manifest.

Source code in src/agents/sandbox/session/sandbox_session_state.py
@redact_mount_error_data_sync
def rebind_persisted_mount_authority(
    self,
    trusted_manifest: Manifest | None,
    *,
    provider_backend_id: str,
) -> SandboxSessionState:
    """Restore redacted mount authority from an exact current trusted manifest."""

    if not self.mount_authority_redacted:
        return self
    if trusted_manifest is None:
        raise ValueError(
            "Sandbox session state contains redacted cloud mount credentials and requires "
            "a current trusted manifest before resume"
        )

    from .._mount_security import rebind_manifest_mount_authority

    rebound_manifest = rebind_manifest_mount_authority(
        self.manifest,
        trusted_manifest,
        provider_backend_id=provider_backend_id,
    )
    rebound = self.model_copy(update={"manifest": rebound_manifest})
    rebound._mount_authority_redacted = False
    rebound._mount_authority_rebound = True
    return rebound