> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Sandbox

> sync/async 하이브리드 API를 제공하는 CWSandbox 클라이언트입니다.

소스: [src/cwsandbox/\_sandbox.py:1688](https://github.com/coreweave/cwsandbox-client/blob/v1.14.2/src/cwsandbox/_sandbox.py#L1688)

```python theme={"system"}
class Sandbox(*, command: str | None = None, args: list[str] | None = None, defaults: SandboxDefaults | None = None, auth: AuthConfig | None = None, container_image: str | None = None, tags: list[str] | None = None, base_url: str | None = None, request_timeout_seconds: float | None = None, poll_retry_budget_seconds: float | None = None, poll_rpc_timeout_seconds: float | None = None, max_lifetime_seconds: float | None = None, profile_ids: list[str] | None = None, profile_names: list[str] | None = None, runner_ids: list[str] | None = None, resources: ResourceOptions | dict[str, Any] | None = None, mounted_files: list[dict[str, Any]] | None = None, s3_mount: dict[str, Any] | None = None, ports: list[dict[str, Any]] | None = None, network: NetworkOptions | dict[str, Any] | None = None, file_system_snapshot: FileSystemSnapshotOptions | dict[str, Any] | None = None, max_timeout_seconds: int | None = None, placement_mode: PlacementMode | str | None = None, placement_spillover: PlacementSpillover | str | None = None, services: list[Service] | tuple[Service, ...] | None = None, volumes: list[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any]] | tuple[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any], ...] | None = None, template_id: str | None = None, image_pull_credentials: ImagePullCredentials | dict[str, Any] | None = None, runtime_class: str | None = None, security_context: SecurityContext | dict[str, Any] | None = None, working_dir: str | None = None, object_storage_access: ObjectStorageAccess | dict[str, Any] | None = None, environment_variables: dict[str, str] | None = None, annotations: dict[str, str] | None = None, secrets: Sequence[Secret | dict[str, Any]] | None = None, data_plane_mode: DataPlaneMode | str | None = None, containers: Sequence[Container | Mapping[str, Any]] | None = None)
```

sync/async 하이브리드 API를 제공하는 CWSandbox 클라이언트입니다.

모든 메서드는 즉시 반환되며 sync 컨텍스트와 async 컨텍스트 모두에서 사용할 수 있습니다.
오퍼레이션은 \_LoopManager가 관리하는 백그라운드 이벤트 루프에서 실행됩니다.

<h2 id="properties">
  속성
</h2>

<h3 id="sandbox_id">
  sandbox\_id
</h3>

```python theme={"system"}
@property
def sandbox_id(self) -> str | None
```

고유한 샌드박스 ID이며, 아직 시작되지 않은 경우 None입니다.

<h3 id="returncode">
  returncode
</h3>

```python theme={"system"}
@property
def returncode(self) -> int | None
```

샌드박스가 완료된 경우 종료 코드이며, 아직 실행 중인 경우 None입니다.

<h3 id="runner_id">
  runner\_id
</h3>

```python theme={"system"}
@property
def runner_id(self) -> str | None
```

샌드박스가 실행 중인 러너이며, 시작되지 않은 경우 None입니다.

<h3 id="status">
  status
</h3>

```python theme={"system"}
@property
def status(self) -> SandboxStatus | None
```

샌드박스의 마지막으로 알려진 상태.

<h3 id="status_updated_at">
  status\_updated\_at
</h3>

```python theme={"system"}
@property
def status_updated_at(self) -> datetime | None
```

상태가 마지막으로 확인된 타임스탬프입니다.

<h3 id="started_at">
  started\_at
</h3>

```python theme={"system"}
@property
def started_at(self) -> datetime | None
```

샌드박스가 시작된 타임스탬프입니다.

<h3 id="runner_group_id">
  runner\_group\_id
</h3>

```python theme={"system"}
@property
def runner_group_id(self) -> str | None
```

샌드박스가 실행 중인 러너 그룹 ID입니다.

<h3 id="service_urls">
  service\_urls
</h3>

```python theme={"system"}
@property
def service_urls(self) -> tuple[tuple[int, str, str], ...]
```

백엔드에서 부여한 서비스별 URL입니다.

<h3 id="service_endpoints">
  service\_endpoints
</h3>

```python theme={"system"}
@property
def service_endpoints(self) -> tuple[HttpsEndpointStatus, ...]
```

생성, 조회 또는 목록 요청에서 반환되는 HTTPS 제품 엔드포인트입니다.

<h3 id="service_addresses">
  service\_addresses
</h3>

```python theme={"system"}
@property
def service_addresses(self) -> tuple[TlsPassthroughEndpointStatus, ...]
```

TLS passthrough 엔드포인트 echoed from create, 조회 또는 목록.

<h3 id="containers">
  containers
</h3>

```python theme={"system"}
@property
def containers(self) -> tuple[Container, ...]
```

샌드박스 리소스에서 에코된 생성 시점의 컨테이너 사양.

<h3 id="container_statuses">
  container\_statuses
</h3>

```python theme={"system"}
@property
def container_statuses(self) -> tuple[ContainerStatus, ...]
```

컨테이너별 관찰된 상태. 샌드박스 `status`는 primary-owned 상태로 유지됩니다.

<h3 id="dns_egress_names">
  dns\_egress\_names
</h3>

```python theme={"system"}
@property
def dns_egress_names(self) -> tuple[str, ...]
```

생성 시 허용된 호스트 이름으로, `status.effective_egress`에서 그대로 반환됩니다.

<h3 id="effective_runtime_class">
  effective\_runtime\_class
</h3>

```python theme={"system"}
@property
def effective_runtime_class(self) -> str | None
```

백엔드에서 적용한 런타임 클래스로, status에서 그대로 가져온 값입니다.

<h3 id="attached_volume_ids">
  attached\_volume\_ids
</h3>

```python theme={"system"}
@property
def attached_volume_ids(self) -> tuple[str, ...]
```

status에서 그대로 반환된, 이 샌드박스에 연결된 등록 볼륨 ID입니다.

<h3 id="effective_egress">
  effective\_egress
</h3>

```python theme={"system"}
@property
def effective_egress(self) -> tuple[EgressRule, ...]
```

`status.effective_egress`에서 에코된 유효한 egress 규칙입니다.

<h3 id="effective_ingress">
  effective\_ingress
</h3>

```python theme={"system"}
@property
def effective_ingress(self) -> tuple[IngressRule, ...]
```

`status.effective_ingress`에서 에코된 effective ingress 규칙.

<h3 id="exposed_ports">
  exposed\_ports
</h3>

```python theme={"system"}
@property
def exposed_ports(self) -> tuple[tuple[int, str], ...] | None
```

유형 지정 서비스에서 파생된 노출된 `(container_port, name)` 쌍.

<h3 id="resource_limits">
  resource\_limits
</h3>

```python theme={"system"}
@property
def resource_limits(self) -> dict[str, str] | None
```

시작 응답의 리소스 제한, 또는 발견된 샌드박스의 경우 None.

<h3 id="resource_requests">
  resource\_requests
</h3>

```python theme={"system"}
@property
def resource_requests(self) -> dict[str, str] | None
```

시작 응답의 리소스 요청, 또는 발견된 샌드박스의 경우 None.

<h3 id="resource_gpu">
  resource\_gpu
</h3>

```python theme={"system"}
@property
def resource_gpu(self) -> dict[str, Any] | None
```

시작 응답에 의해 확인된 GPU 설정이거나, discovered 샌드박스의 경우 None입니다.

<h3 id="file_system_snapshot_id">
  file\_system\_snapshot\_id
</h3>

```python theme={"system"}
@property
def file_system_snapshot_id(self) -> str | None
```

`stop(snapshot_on_stop=True)`에 의해 생성된 스냅샷의 ID.

<h3 id="exec_stats">
  exec\_stats
</h3>

```python theme={"system"}
@property
def exec_stats(self) -> dict[str, int]
```

이 샌드박스의 실행 통계입니다.

<h2 id="methods">
  메서드
</h2>

<h3 id="run">
  run
</h3>

```python theme={"system"}
run(*args: str = (), container_image: str | None = None, defaults: SandboxDefaults | None = None, auth: AuthConfig | None = None, request_timeout_seconds: float | None = None, poll_retry_budget_seconds: float | None = None, poll_rpc_timeout_seconds: float | None = None, max_lifetime_seconds: float | None = None, tags: list[str] | None = None, profile_ids: list[str] | None = None, profile_names: list[str] | None = None, runner_ids: list[str] | None = None, resources: ResourceOptions | dict[str, Any] | None = None, mounted_files: list[dict[str, Any]] | None = None, s3_mount: dict[str, Any] | None = None, ports: list[dict[str, Any]] | None = None, network: NetworkOptions | dict[str, Any] | None = None, file_system_snapshot: FileSystemSnapshotOptions | dict[str, Any] | None = None, max_timeout_seconds: int | None = None, placement_mode: PlacementMode | str | None = None, placement_spillover: PlacementSpillover | str | None = None, services: list[Service] | tuple[Service, ...] | None = None, volumes: list[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any]] | tuple[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any], ...] | None = None, template_id: str | None = None, image_pull_credentials: ImagePullCredentials | dict[str, Any] | None = None, runtime_class: str | None = None, security_context: SecurityContext | dict[str, Any] | None = None, working_dir: str | None = None, object_storage_access: ObjectStorageAccess | dict[str, Any] | None = None, environment_variables: dict[str, str] | None = None, annotations: dict[str, str] | None = None, secrets: Sequence[Secret | dict[str, Any]] | None = None, data_plane_mode: DataPlaneMode | str | None = None, containers: Sequence[Container | Mapping[str, Any]] | None = None) -> Sandbox
```

샌드박스를 생성하고 시작하며, 백엔드가 요청을 수락하면 즉시 반환합니다.

RUNNING 상태가 될 때까지 기다리지 않습니다. 준비될 때까지 실행을 차단하려면 .wait()를 사용하세요.
위치 인수가 제공되면 첫 번째 인수는 명령이고 나머지는
해당 명령의 인수입니다. 인수가 제공되지 않으면 중지 시 SIGTERM에 응답하는
셸 트랩 기반의 기본 연결 유지 명령을 사용합니다.
**매개변수**

* `*args` (`str`): 선택 명령 및 인수(예: "echo", "hello", "world"). 생략하면 SandboxDefaults의 기본 명령을 사용합니다.
* `container_image` (`str | None`): 사용할 컨테이너 이미지
* `defaults` (`SandboxDefaults | None`): 적용할 선택 SandboxDefaults
* `auth` (`AuthConfig | None`): 인증 모드 또는 공급자. `defaults.auth`를 재정의합니다.
* `request_timeout_seconds` (`float | None`): API 요청의 timeout(클라이언트 측)
* `poll_retry_budget_seconds` (`float | None`): 샌드박스 상태 폴링 루프에서 일시적인 오류를 재시도할 수 있는 실제 경과 시간 한도(기본값: 30초). 재시도를 비활성화하려면 0으로 설정하세요.
* `poll_rpc_timeout_seconds` (`float | None`): 폴링 조회 RPC의 호출별 timeout(기본값: 15초). request\_timeout\_seconds와 별개입니다.
* `max_lifetime_seconds` (`float | None`): 최대 샌드박스 수명(서버 측)
* `tags` (`list[str] | None`): 샌드박스의 선택 태그
* `profile_ids` (`list[str] | None`): 1.x에서 제거되었습니다. 값을 전달하면 `TypeError`가 발생합니다.
* `profile_names` (`list[str] | None`): 1.x에서 제거되었습니다. 값을 전달하면 `TypeError`가 발생합니다.
* `runner_ids` (`list[str] | None`): 선택 CKS 러너 고정(서버리스 및 `placement_spillover='serverless_then_cks'`와 호환되지 않음).
* `resources` (`ResourceOptions | dict[str, Any] | None`): 리소스 설정. 요청량과 한도를 별도로 지정하는 ResourceOptions 또는 이전 버전과 호환되는 Guaranteed QoS를 위한 평면 dict를 받습니다.
* `mounted_files` (`list[dict[str, Any]] | None`): 시작 시 샌드박스에 마운트할 파일. 각 dict에는 `mount_path`(str)와 `file_content`(bytes)가 있어야 합니다. 참고: 마운트된 파일은 런타임에 읽기 전용입니다. 파일을 수정하려면 샌드박스가 실행된 후 `sandbox.write_file()`을 사용하세요.
* `s3_mount` (`dict[str, Any] | None`): 1.x에서 제거되었습니다. 값을 전달하면 `TypeError`가 발생합니다.
* `ports` (`list[dict[str, Any]] | None`): 1.x에서 제거되었습니다. 대신 `services=[Service(...)]`를 사용하세요.
* `network` (`NetworkOptions | dict[str, Any] | None`): 거부 플래그와 생성 시 선택적으로 지정하는 호스트 이름 허용 규칙(`egress=[EgressRule(dns_name=...)]`)을 포함하는 `NetworkOptions`(또는 dict). 포트 노출에는 `services=`를 사용합니다.
* `placement_mode` (`PlacementMode | str | None`): `PlacementMode` 또는 string(`serverless` / `cks`).
* `placement_spillover` (`PlacementSpillover | str | None`): `PlacementSpillover` 또는 string. 기본값은 `strict`입니다. `Sandbox.__init__`을 참조하세요.
* `services` (`list[Service] | tuple[Service, ...] | None`): 유형 지정 서비스 포트(`Service` 목록/튜플).
* `volumes` (`list[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any]] | tuple[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any], ...] | None`): 스크래치 또는 등록된 볼륨(`ScratchVolumeOptions`, `RegisteredVolumeOptions` 또는 `volume_id` dict).
* `runtime_class` (`str | None`): 선택 런타임 클래스 고정(예: `"gvisor"`).
* `security_context` (`SecurityContext | dict[str, Any] | None`): 기본 컨테이너의 게스트 내부 권한.
* `working_dir` (`str | None`): 기본 컨테이너 명령의 작업 디렉터리.
* `object_storage_access` (`ObjectStorageAccess | dict[str, Any] | None`): 임시 객체 저장소 인증 정보.
* `file_system_snapshot` (`FileSystemSnapshotOptions | dict[str, Any] | None`): 편의용 단일 마운트 FSS 옵션(`FileSystemSnapshotOptions` 또는 dict)입니다. 다중 볼륨 설정에는 `volumes=`를 사용하는 것이 좋습니다.
* `max_timeout_seconds` (`int | None`): 1.x에서 제거되었습니다. `request_timeout_seconds`를 사용하세요.
* `environment_variables` (`dict[str, str] | None`): 샌드박스에 주입할 환경 변수입니다. 세션 기본값과 병합되며, 키가 겹치면 이 값이 우선합니다. 민감하지 않은 설정에만 사용하세요.
* `annotations` (`dict[str, str] | None`): 샌드박스의 Kubernetes 파드 어노테이션입니다. 세션 기본값과 병합되며, 키가 겹치면 이 값이 우선합니다. 민감하지 않은 메타데이터에만 사용하세요.
* `secrets` (`Sequence[Secret | dict[str, Any]] | None`): 생성 시 환경 변수로 주입할 시크릿입니다. 기본값과 병합됩니다(기본값이 먼저 적용되고 그다음에 이 목록이 적용됨).
* `data_plane_mode` (`DataPlaneMode | str | None`): exec, 로그, 파일 오퍼레이션에 사용할 전송 정책입니다. `auto`는 직접 mTLS 연결을 우선 사용하고, 실패하면 게이트웨이로 대체합니다.
* `containers` (`Sequence[Container | Mapping[str, Any]] | None`): 다중 컨테이너 사양입니다. 위치 인수 command/args와 함께 사용할 수 없으며, `container_image`, `resources`, `mounted_files`, `secrets`, `image_pull_credentials`, `environment_variables`, `security_context`, `working_dir`와도 함께 사용할 수 없습니다. 이 목록은 `SandboxDefaults`의 같은 이름 필드를 포함해 이러한 단일 컨테이너 필드를 대체합니다. secrets, env, working\_dir는 각 `Container`에 지정하세요.

반환값:
Sandbox 인스턴스(시작 요청은 전송되었지만 아직 시작 중일 수 있음)
**예시**

```python theme={"system"}
# 기본값 사용 (셸 트랩 방식의 keep-alive)
sb = Sandbox.run()

# fire-and-forget 방식
sb = Sandbox.run("echo", "hello")
# sb.sandbox_id는 설정되지만 샌드박스는 아직 시작 중일 수 있습니다

# 필요하면 준비 상태가 될 때까지 대기
sb = Sandbox.run("sleep", "infinity").wait()
result = sb.exec(["echo", "hello"]).result()

# 또는 컨텍스트 관리자를 사용해 자동으로 정리
with Sandbox.run("sleep", "infinity") as sb:
    result = sb.exec(["echo", "hello"]).result()
```

<h3 id="run_from_template">
  run\_from\_template
</h3>

```python theme={"system"}
run_from_template(template_id: str, *args: str = (), command: str | None = None, defaults: SandboxDefaults | None = None, **kwargs: Any = {}) -> Sandbox
```

조직 템플릿에서 샌드박스를 생성합니다(CreateSandboxFromTemplate).
**매개변수**

* `template_id` (`str`): 조직 범위의 템플릿 UUID입니다.
* `*args` (`str`): 명령 인수를 재정의합니다(선택 사항). `command` 없이도 적용됩니다. 단, 부분적인 단일 컨테이너 오버레이에는 여전히 `container_image`가 필요합니다.
* `command` (`str | None`): 명령을 재정의합니다(선택 사항). `containers=`로 목록 전체를 대체하는 경우가 아니라면 `container_image`가 필요합니다.
* `defaults` (`SandboxDefaults | None`): SandboxDefaults입니다(선택 사항).
* `**kwargs` (`Any`): `run()`과 동일한 고급 생성 kwargs입니다. `container_image`를 전달하면 템플릿 컨테이너 전체(command, args, env, files, resources, 이름 `main`)가 대체되며, 기존 값을 가져와 병합하지는 않습니다. `containers=`는 목록 전체를 대체하며 `container_image`가 필요하지 않습니다. 그 밖의 컨테이너 필드 오버레이(`command`, `args`, `environment_variables`, `secrets`, `resources`, `mounted_files`, `volumes`, `file_system_snapshot`, `image_pull_credentials`, `security_context`, `working_dir`)는 `containers=`로 목록을 대체하는 경우가 아니라면 `container_image`가 필요합니다. API가 컨테이너 목록 전체를 대체하므로 부분 패치는 거부되기 때문입니다. 세션/기본 태그는 병합된 후, 값이 있으면 대체하는 방식의 재정의로 전송되므로 `list()`/`adopt`로 샌드박스를 찾을 수 있습니다. 환경 변수와 어노테이션은 템플릿에 속하므로 병합되지 않습니다.

**반환값**

* `Sandbox`: 샌드박스 핸들(지연 시작)입니다.

<h3 id="run_from_file">
  run\_from\_file
</h3>

```python theme={"system"}
run_from_file(contents: str | Path | bytes, *, primary_service: str, file_type: SandboxFileType | str = SandboxFileType.COMPOSE, image_overrides: Mapping[str, str] | None = None, default_resources: ResourceOptions | dict[str, Any] | None = None, defaults: SandboxDefaults | None = None, auth: AuthConfig | None = None, request_timeout_seconds: float | None = None, poll_retry_budget_seconds: float | None = None, poll_rpc_timeout_seconds: float | None = None, max_lifetime_seconds: float | None = None, tags: list[str] | None = None, runner_ids: list[str] | None = None, network: NetworkOptions | dict[str, Any] | None = None, placement_mode: PlacementMode | str | None = None, placement_spillover: PlacementSpillover | str | None = None, object_storage_access: ObjectStorageAccess | dict[str, Any] | None = None, annotations: dict[str, str] | None = None, request_id: str | None = None, data_plane_mode: DataPlaneMode | str | None = None, **kwargs: Any = {}) -> Sandbox
```

업로드한 파일에서 샌드박스를 생성합니다(CreateSandboxFromFile).

v1 Compose만 지원하며, 가져오기 전용 이미지만 사용합니다. `contents`를 원시 바이트로 읽고
YAML을 정규화하지 않습니다. 동일한 `request_id`에 다른 바이트를 사용하면
(공백만 수정한 경우 포함) `CWSANDBOX_REQUEST_ID_CONFLICT`가 발생합니다.
백엔드가 요청을 수락하면 즉시 반환합니다. RUNNING 상태를 기다리려면
`wait()`를 다시 사용하세요. `PREPARING` 상태를 기다리지 마세요.

GetSandbox는 원본 파일이 아닌 변환된 사양을 반환합니다. Compose
`build:`가 남아 있으면 `CWSANDBOX_NOT_IMPLEMENTED`가 발생합니다. YAML에서
`image:`를 설정하거나 `image_overrides`를 설정하여 빌드를 건너뛰세요.
**매개변수**

* `contents` (`str | Path | bytes`): Compose 파일 경로(`str` / `Path`) 또는 원시 YAML 바이트입니다. `str`은 항상 경로로 열립니다. Compose 텍스트는 `bytes`로 전달하세요(`.encode("utf-8")`). 한도는 256 KiB입니다. 바이트는 그대로 전송됩니다.
* `primary_service` (`str`): 샌드박스의 기본 서비스로 사용할 Compose 서비스입니다.
* `file_type` (`SandboxFileType | str`): 문서 유형입니다. 기본값은 `compose`입니다.
* `image_overrides` (`Mapping[str, str] | None`): 서비스별로 가져올 수 있는 이미지 참조입니다. 키는 `contents`에 있는 서비스여야 합니다.
* `default_resources` (`ResourceOptions | dict[str, Any] | None`): `deploy.resources`를 생략한 각 서비스에 복사되는 CPU/메모리입니다. 프로젝트의 리소스 한도가 아닌 컨테이너별 설정입니다. GPU는 로컬에서 거부됩니다(게이트웨이에서도 거부됩니다).
* `defaults` (`SandboxDefaults | None`): 선택 사항인 `SandboxDefaults`입니다. 태그, 네트워크, `placement_mode`, `runner_ids`, 어노테이션, 객체 저장소 액세스, 최대 수명은 상속됩니다. 컨테이너/볼륨/ 서비스 기본값은 상속되지 않습니다. 기본값에 지정된 비엄격 `placement_spillover`는 무시됩니다(파일 기반 생성은 항상 엄격 모드입니다). 비엄격 모드를 명시하는 키워드 인수를 전달하면 예외가 발생합니다.
* `request_id` (`str | None`): 선택 사항인 멱등성 토큰입니다. 생략하면 자동 생성됩니다.
* `**kwargs` (`Any`): 거부됩니다. 이 RPC는 볼륨, 공개 서비스, `runtime_class`, `image_pull_credentials`, `network_ids`, `build_contexts`를 허용하지 않습니다.

**반환값**

* `Sandbox`: 샌드박스 핸들입니다(생성이 수락되었으며, 아직 시작 중일 수 있습니다).

<h3 id="session">
  session
</h3>

```python theme={"system"}
session(defaults: SandboxDefaults | Mapping[str, Any] | None = None, *, auth: AuthConfig | None = None) -> Session
```

여러 샌드박스를 관리할 세션을 생성합니다.

세션은 다음을 제공합니다:

* 기본값을 통한 공유 설정

* 고아 샌드박스 자동 정리

* @session.function() 데코레이터를 통한 함수 실행
  **매개변수**

* `defaults` (`SandboxDefaults | Mapping[str, Any] | None`): 세션을 통해 생성된 샌드박스에 적용할 선택적 기본값

* `auth` (`AuthConfig | None`): 인증 전략, 확인된 헤더 또는 공급자입니다. 제공하면 `defaults.auth`를 재정의합니다.

**반환값**

* `Session`: 세션 인스턴스

**예시**

```python theme={"system"}
session = Sandbox.session(defaults)
sb = session.create(command="sleep", args=["infinity"])

@session.function()
def compute(x, y):
    return x + y

await session.close()
```

<h3 id="list">
  list
</h3>

```python theme={"system"}
list(*, tags: list[str] | None = None, status: str | None = None, profile_ids: list[str] | None = None, profile_names: list[str] | None = None, runner_ids: list[str] | None = None, show_terminated: bool = False, base_url: str | None = None, auth: AuthConfig | None = None, timeout_seconds: float | None = None, poll_retry_budget_seconds: float | None = None, poll_rpc_timeout_seconds: float | None = None, data_plane_mode: DataPlaneMode | str = DataPlaneMode.AUTO, volume_ids: list[str] | tuple[str, ...] | None = None) -> OperationRef[list[Sandbox]]
```

기존 샌드박스를 선택적 필터와 함께 목록으로 조회합니다.

exec(), stop(), get\_status(), read\_file(), write\_file() 등의 오퍼레이션에 사용할 수 있는 Sandbox 인스턴스로 확인되는 OperationRef을 반환합니다.

기본적으로 active(종료되지 않은) 샌드박스만 반환됩니다.
`show_terminated=True`로 설정하면 종료된 샌드박스(completed, failed, terminated)를 포함하도록 검색 범위를 넓힙니다.
종료 상태 필터(예: `status="completed"`)를 사용해도 검색 범위가 자동으로 넓어집니다.
**매개변수**

* `tags` (`list[str] | None`): 태그로 필터링 (샌드박스가 지정된 모든 태그를 보유해야 함)
* `status` (`str | None`): 상태로 필터링 ("running", "completed", "failed" 등)
* `profile_ids` (`list[str] | None`): 1.x에서 제거됨. 값을 전달하면 `TypeError`가 발생합니다.
* `profile_names` (`list[str] | None`): 1.x에서 제거됨. 값을 전달하면 `TypeError`가 발생합니다.
* `runner_ids` (`list[str] | None`): 러너 ID로 필터링
* `volume_ids` (`list[str] | tuple[str, ...] | None`): 지정된 등록된 볼륨 ID에 연결된 샌드박스로 필터링
* `show_terminated` (`bool`): True인 경우 종료된 샌드박스(completed, failed, terminated)를 포함합니다. 기본값은 False입니다.
* `base_url` (`str | None`): API URL 재정의 (기본값: CWSANDBOX\_BASE\_URL 환경 변수 또는 기본값)
* `auth` (`AuthConfig | None`): 인증 전략, 이 요청에 대한 확인된 헤더 또는 공급자.
* `timeout_seconds` (`float | None`): 요청 timeout (기본값: 300s)
* `poll_retry_budget_seconds` (`float | None`): 샌드박스 상태 폴링 루프에서 일시적 오류 재시도를 위한 실제 경과 시간 예산 (기본값: 30s). 재시도를 비활성화하려면 0으로 설정합니다. 반환된 Sandbox 인스턴스에 적용됩니다.
* `poll_rpc_timeout_seconds` (`float | None`): 폴링 조회 RPC당 timeout (기본값: 15s). `timeout_seconds`와 별개입니다. 반환된 Sandbox 인스턴스에 적용됩니다.
* `data_plane_mode` (`DataPlaneMode | str`): 반환된 샌드박스에 적용되는 전송 정책.

**반환값**

* `OperationRef[list[Sandbox]]`: OperationRef\[list\[Sandbox]]: 결과를 기다리려면 .result()를 사용하거나,
* `OperationRef[list[Sandbox]]`: 비동기 컨텍스트에서는 직접 await합니다.

**예시**

```python theme={"system"}
# 동기 방식 사용 - 활성 샌드박스만 조회 (기본값)
sandboxes = Sandbox.list(tags=["my-batch-job"]).result()
for sb in sandboxes:
    print(f"{sb.sandbox_id}: {sb.status}")
    sb.stop().result()

# 중단된 샌드박스 포함
all_sandboxes = Sandbox.list(
    tags=["my-batch-job"], show_terminated=True
).result()

# 비동기 방식 사용
sandboxes = await Sandbox.list(status="running")
for sb in sandboxes:
    result = await sb.exec(["echo", "hello"])
```

<h3 id="from_id">
  from\_id
</h3>

```python theme={"system"}
from_id(sandbox_id: str, *, base_url: str | None = None, auth: AuthConfig | None = None, timeout_seconds: float | None = None, poll_retry_budget_seconds: float | None = None, poll_rpc_timeout_seconds: float | None = None, data_plane_mode: DataPlaneMode | str = DataPlaneMode.AUTO) -> OperationRef[Sandbox]
```

기존 샌드박스에 ID로 연결합니다.

기존 샌드박스에 연결된 Sandbox 인스턴스를 생성하여
exec(), stop(), get\_status() 등과 같은 오퍼레이션을 허용합니다.
**매개변수**

* `sandbox_id` (`str`): 기존 샌드박스의 ID
* `base_url` (`str | None`): API URL 재정의 (기본값: CWSANDBOX\_BASE\_URL 환경 변수 또는 기본값)
* `auth` (`AuthConfig | None`): 인증 전략, 확인된 헤더, 또는 이 요청의 공급자.
* `timeout_seconds` (`float | None`): 요청 timeout (기본값: 300s)
* `poll_retry_budget_seconds` (`float | None`): 샌드박스 상태 폴링 루프에서 일시적 오류 재시도를 위한 실제 경과 시간 예산 (기본값: 30s). 0으로 설정하면 재시도를 비활성화합니다. 반환된 Sandbox 인스턴스에 적용됩니다.
* `poll_rpc_timeout_seconds` (`float | None`): 폴링 조회 RPC의 호출당 timeout (기본값: 15s). `timeout_seconds`와 별개입니다. 반환된 Sandbox 인스턴스에 적용됩니다.
* `data_plane_mode` (`DataPlaneMode | str`): 반환된 샌드박스에 적용되는 전송 정책.

**반환값**

* `OperationRef[Sandbox]`: .result()를 사용하여 Sandbox 인스턴스를 기다립니다.
* `OperationRef[Sandbox]`: 또는 비동기 컨텍스트에서 직접 await합니다.

**예외**

* `SandboxNotFoundError`: 샌드박스가 존재하지 않는 경우

**예시**

```python theme={"system"}
# 동기 방식 사용
sb = Sandbox.from_id("sandbox-abc123").result()
result = sb.exec(["python", "-c", "print('hello')"]).result()
sb.stop().result()

# 비동기 방식 사용
sb = await Sandbox.from_id("sandbox-abc123")
result = await sb.exec(["python", "-c", "print('hello')"])
```

<h3 id="delete">
  delete
</h3>

```python theme={"system"}
delete(sandbox_id: str, *, base_url: str | None = None, auth: AuthConfig | None = None, timeout_seconds: float | None = None, missing_ok: bool = False) -> OperationRef[None]
```

Sandbox 인스턴스를 생성하지 않고 ID로 샌드박스를 삭제합니다.

샌드박스에서 다른 오퍼레이션을 수행할 필요가 없는
정리 작업에 편리하게 사용할 수 있는 방법입니다.
**매개변수**

* `sandbox_id` (`str`): 삭제할 샌드박스 ID
* `base_url` (`str | None`): API URL 재정의 (기본값: CWSANDBOX\_BASE\_URL 환경 변수 또는 기본값)
* `auth` (`AuthConfig | None`): 이 요청의 인증 전략, 확인된 헤더 또는 공급자.
* `timeout_seconds` (`float | None`): 요청 timeout (기본값: 300초)
* `missing_ok` (`bool`): True이면 샌드박스가 존재하지 않을 때 SandboxNotFoundError를 발생시키지 않습니다.

**반환값**

* `OperationRef[None]`: OperationRef\[None]: 완료될 때까지 대기하려면 .result()를 사용하세요.
* `OperationRef[None]`: 찾을 수 없으면 SandboxNotFoundError가 발생합니다 (missing\_ok=True인 경우 제외).
* `OperationRef[None]`: 삭제에 실패하면 SandboxError가 발생합니다.

**예외**

* `SandboxNotFoundError`: 샌드박스가 존재하지 않고 missing\_ok=False인 경우
* `SandboxError`: 다른 이유로 삭제에 실패한 경우

**예시**

```python theme={"system"}
# 동기 사용
Sandbox.delete("sandbox-abc123").result()

# 이미 삭제된 경우 무시
Sandbox.delete("sandbox-abc123", missing_ok=True).result()

# 비동기 사용
await Sandbox.delete("sandbox-abc123")
```

<h3 id="get_snapshot">
  get\_snapshot
</h3>

```python theme={"system"}
get_snapshot(file_system_snapshot_id: str, *, base_url: str | None = None, auth: AuthConfig | None = None, timeout_seconds: float | None = None) -> OperationRef[FileSystemSnapshot]
```

ID로 파일 시스템 스냅샷(FSS) 레코드를 가져옵니다.

스냅샷의 범위는 조직으로 한정됩니다. 조직이 소유한 모든 스냅샷은
어떤 샌드박스에서 생성했는지와 관계없이 볼 수 있습니다.
**매개변수**

* `file_system_snapshot_id` (`str`): 가져올 스냅샷 ID입니다.
* `base_url` (`str | None`): API URL 재정의(기본값: CWSANDBOX\_BASE\_URL 환경 변수 또는 기본값).
* `auth` (`AuthConfig | None`): 이 요청의 인증 전략, 확인된 헤더 또는 공급자입니다.
* `timeout_seconds` (`float | None`): 요청 timeout(기본값: 300초).

**반환값**

* `OperationRef[FileSystemSnapshot]`: OperationRef\[FileSystemSnapshot]: .result()를 사용하여 완료될 때까지 대기하거나 await를 사용하세요.
* `OperationRef[FileSystemSnapshot]`: 스냅샷이 존재하지 않으면 SnapshotNotFoundError가 발생합니다.

**예시**

```python theme={"system"}
snap = Sandbox.get_snapshot("fss-abc123").result()
print(snap.status, snap.size_bytes)
```

<h3 id="list_snapshots">
  list\_snapshots
</h3>

```python theme={"system"}
list_snapshots(*, source_sandbox_id: str | None = None, status: FileSystemSnapshotStatus | str | None = None, base_url: str | None = None, auth: AuthConfig | None = None, timeout_seconds: float | None = None) -> OperationRef[list[FileSystemSnapshot]]
```

조직의 파일 시스템 스냅샷(FSS)을 목록으로 표시합니다.

스냅샷은 조직 범위이며 목록은 자동 페이지 매김됩니다.
`source_sandbox_id` 및 `status` 필터는 클라이언트 측에서 적용됩니다.
(백엔드 목록 RPC는 필터링하지 않음) 따라서 모든 스냅샷을 가져온 후
필터링합니다.
**매개변수**

* `source_sandbox_id` (`str | None`): 설정된 경우, 이 샌드박스에서 캡처된 스냅샷만 포함합니다.
* `status` (`FileSystemSnapshotStatus | str | None`): 설정된 경우, 이 상태의 스냅샷만 포함합니다 (FileSystemSnapshotStatus 또는 해당 string 값).
* `base_url` (`str | None`): API URL 재정의 (기본값: CWSANDBOX\_BASE\_URL 환경 변수 또는 기본값).
* `auth` (`AuthConfig | None`): 이 요청에 대한 인증 전략, 확인된 헤더 또는 공급자입니다.
* `timeout_seconds` (`float | None`): 요청 timeout (기본값: 300s).

**반환값**

* `OperationRef[list[FileSystemSnapshot]]`: OperationRef\[list\[FileSystemSnapshot]]: .result()를 사용하여 대기하거나 await합니다.

**예시**

```python theme={"system"}
# 주어진 샌드박스에서 모든 준비 완료 상태의 스냅샷
snaps = Sandbox.list_snapshots(
    source_sandbox_id=sb.sandbox_id,
    status=FileSystemSnapshotStatus.READY,
).result()
```

<h3 id="delete_snapshot">
  delete\_snapshot
</h3>

```python theme={"system"}
delete_snapshot(file_system_snapshot_id: str, *, base_url: str | None = None, auth: AuthConfig | None = None, timeout_seconds: float | None = None, missing_ok: bool = False) -> OperationRef[None]
```

ID로 파일 시스템 스냅샷(FSS)을 삭제합니다.

스냅샷을 삭제해도 해당 스냅샷에서 이미 복원된 샌드박스에는 영향을 주지 않습니다.
**매개변수**

* `file_system_snapshot_id` (`str`): 삭제할 스냅샷 ID입니다.
* `base_url` (`str | None`): API URL을 재정의합니다(기본값: CWSANDBOX\_BASE\_URL 환경 변수 또는 기본값).
* `auth` (`AuthConfig | None`): 이 요청에 사용할 인증 전략, 확인된 헤더 또는 공급자입니다.
* `timeout_seconds` (`float | None`): 요청 timeout입니다(기본값: 300초).
* `missing_ok` (`bool`): True이면 스냅샷이 존재하지 않을 때(이미 삭제된 경우) SnapshotNotFoundError를 발생시키지 않습니다.

**반환값**

* `OperationRef[None]`: OperationRef\[None]: 블로킹하거나 await하려면 .result()를 사용하세요.
* `OperationRef[None]`: 스냅샷을 찾을 수 없으면 SnapshotNotFoundError를 발생시킵니다(missing\_ok=True인 경우 제외).

**예시**

```python theme={"system"}
Sandbox.delete_snapshot("fss-abc123").result()
Sandbox.delete_snapshot("fss-abc123", missing_ok=True).result()
```

<h3 id="get_snapshot_bucket_config">
  get\_snapshot\_bucket\_config
</h3>

```python theme={"system"}
get_snapshot_bucket_config(*, base_url: str | None = None, auth: AuthConfig | None = None, timeout_seconds: float | None = None) -> OperationRef[FileSystemSnapshotBucketConfig]
```

조직의 FSS 객체 저장소 버킷 설정을 가져옵니다.
**매개변수**

* `base_url` (`str | None`): API URL 재정의 (기본값: CWSANDBOX\_BASE\_URL 환경 변수 또는 기본값).
* `auth` (`AuthConfig | None`): 이 요청의 인증 전략, 확인된 헤더 또는 공급자.
* `timeout_seconds` (`float | None`): 요청 timeout (기본값: 300초).

**반환값**

* `OperationRef[FileSystemSnapshotBucketConfig]`: OperationRef\[FileSystemSnapshotBucketConfig]: .result() 또는 await를 사용하세요.

**예시**

```python theme={"system"}
cfg = Sandbox.get_snapshot_bucket_config().result()
print(cfg.mode, cfg.effective_bucket_name)
```

<h3 id="set_snapshot_bucket_config">
  set\_snapshot\_bucket\_config
</h3>

```python theme={"system"}
set_snapshot_bucket_config(*, bucket_name: str, region: str = '', base_url: str | None = None, auth: AuthConfig | None = None, timeout_seconds: float | None = None) -> OperationRef[FileSystemSnapshotBucketConfig]
```

조직의 FSS 객체 저장소 버킷 설정을 지정합니다.

직접 보유한 버킷(BYOB)을 사용하려면 `bucket_name`을 지정하고, CoreWeave 관리형 버킷으로 되돌리려면 빈
문자열을 전달하세요. 이
오퍼레이션은 Admin 권한이 필요합니다.
**매개변수**

* `bucket_name` (`str`): 스냅샷을 보관할 버킷입니다. 빈 문자열을 전달하면 CoreWeave 관리형 버킷으로 되돌립니다.
* `region` (`str`): 버킷 리전입니다(일부 공급자는 BYO 버킷에 이 값이 필요합니다).
* `base_url` (`str | None`): 기본 URL 대신 사용할 API URL입니다(기본값: CWSANDBOX\_BASE\_URL 환경 변수 또는 기본값).
* `auth` (`AuthConfig | None`): 이 요청에 사용할 인증 전략, 확인된 헤더 또는 공급자입니다.
* `timeout_seconds` (`float | None`): 요청 timeout입니다(기본값: 300초).

**반환값**

* `OperationRef[FileSystemSnapshotBucketConfig]`: OperationRef\[FileSystemSnapshotBucketConfig]: 업데이트된 설정입니다.

**예시**

```python theme={"system"}
# 직접 보유한 버킷 사용
Sandbox.set_snapshot_bucket_config(
    bucket_name="my-org-fss", region="us-east-1"
).result()

# CoreWeave 관리형 버킷으로 되돌리기
Sandbox.set_snapshot_bucket_config(bucket_name="").result()
```

<h3 id="get_status">
  get\_status
</h3>

```python theme={"system"}
get_status() -> SandboxStatus
```

샌드박스의 현재 상태를 조회합니다.

종료 상태의 샌드박스(COMPLETED/FAILED/TERMINATED)는 API 호출 없이 캐시된
상태를 반환합니다. 활성 샌드박스는 백엔드에서 상태를 가져옵니다.
**반환값**

* `SandboxStatus`: SandboxStatus 열거형 값

**예외**

* `SandboxNotRunningError`: 샌드박스가 시작되지 않은 경우

**예시**

```python theme={"system"}
sb = Sandbox.run("sleep", "10")
status = sb.get_status()
print(f"Sandbox is {status}")  # SandboxStatus.PENDING 또는 RUNNING
```

<h3 id="start">
  start
</h3>

```python theme={"system"}
start() -> OperationRef[None]
```

StartSandbox를 백엔드로 보내고 OperationRef를 즉시 반환합니다.

RUNNING 상태가 될 때까지 기다리지 않습니다. 준비될 때까지 대기하려면 wait()를 사용하세요.
시작 요청이 수락될 때까지 대기하려면 .result()를 호출하세요.
**반환값**

* `OperationRef[None]`: OperationRef\[None]: 백엔드가 수락할 때까지 대기하려면 .result()를 사용하세요.

**예시**

```python theme={"system"}
sandbox = Sandbox(command="sleep", args=["infinity"])
sandbox.start().result()
print(f"Started sandbox: {sandbox.sandbox_id}")
sandbox.wait()  # RUNNING 상태가 될 때까지 대기
```

<h3 id="wait">
  wait
</h3>

```python theme={"system"}
wait(timeout: float | None = None) -> Sandbox
```

샌드박스가 RUNNING 또는 종료 상태에 도달할 때까지 대기합니다.

샌드박스가 RUNNING 상태이거나 이미 완료된 경우(COMPLETED/UNSPECIFIED) 반환합니다.
**매개변수**

* `timeout` (`float | None`): 최대 대기 시간(초)입니다. None이면 기본 timeout을 사용합니다.

**반환값**

* `Sandbox`: 방법 체이닝을 위한 자기 자신입니다. .status를 확인하여 최종 상태를 확인하세요.

**예외**

* `SandboxFailedError`: 샌드박스를 시작하지 못한 경우
* `SandboxTerminatedError`: 샌드박스가 외부에서 종료된 경우
* `SandboxTimeoutError`: timeout이 만료된 경우

**예시**

```python theme={"system"}
sb = Sandbox.run("sleep", "infinity").wait()
result = sb.exec(["echo", "ready"]).result()
```

<h3 id="wait_until_complete">
  wait\_until\_complete
</h3>

```python theme={"system"}
wait_until_complete(timeout: float | None = None, *, raise_on_termination: bool = True) -> OperationRef[Sandbox]
```

샌드박스가 종료 상태(COMPLETED/FAILED/TERMINATED)에 도달할 때까지 기다립니다.

샌드박스가 종료 상태에 도달하면 완료되는 OperationRef를 반환합니다.
완료 후 백엔드가 반환 코드를
기록했다면 returncode를 사용할 수 있습니다(None으로
유지되는 경우는 `returncode` 속성을 참조하세요).
**매개변수**

* `timeout` (`float | None`): 대기할 최대 시간(초)입니다. None이면 기본 timeout을 사용합니다.
* `raise_on_termination` (`bool`): True(기본값)이면 이 클라이언트가 stop()을 호출했거나 백엔드가 레거시 TERMINATED 상태를 보고할 때 SandboxTerminatedError가 발생합니다. COMPLETED로 이어지는 외부 종료(인프라, 수명 제한, 다른 클라이언트)는 백엔드가 termination\_reason 메타데이터를 제공하기 전까지 감지할 수 없습니다. SandboxTerminatedError를 완전히 억제하려면 False로 설정하세요.

**반환값**

* `OperationRef[Sandbox]`: OperationRef\[Sandbox]: .result()를 사용하여 실행을 차단하거나 비동기 컨텍스트에서 await하세요.

**예외**

* `SandboxTimeoutError`: timeout이 만료된 경우
* `SandboxTerminatedError`: 이 클라이언트가 샌드박스를 중단했거나 백엔드가 TERMINATED로 보고한 경우(raise\_on\_termination=True인 경우)
* `SandboxFailedError`: 샌드박스가 실패한 경우

**참고:** `poll_retry_budget_seconds`는 사용자의 `timeout` 매개변수 내에서 적용되는 엄격한 하위 timeout입니다. 사용자 timeout이 300초이고 재시도 허용 시간이 30초이면 약 30초 후에 허용 시간 소진 오류가 발생할 수 있습니다. 더 오래 재시도하려는 호출자는 이에 맞게 `poll_retry_budget_seconds`를 설정해야 합니다.

**예시**

```python theme={"system"}
sb = Sandbox.run("python", "-c", "print('done')")
sb.wait_until_complete().result()
print(f"Exit code: {sb.returncode}")
```

<h3 id="stop">
  stop
</h3>

```python theme={"system"}
stop(*, snapshot_on_stop: bool = False, graceful_shutdown_seconds: float = DEFAULT_GRACEFUL_SHUTDOWN_SECONDS, missing_ok: bool = False, wait_for_ready: bool = True, request_id: str | None = None) -> OperationRef[None]
```

샌드박스를 중단하고 즉시 OperationRef를 반환합니다.

샌드박스는 TERMINATING(유예 기간 드레인)을 거칩니다.
그 후 종료 상태(COMPLETED 또는 FAILED)에 도달합니다. 반환된
OperationRef는 stop RPC가 성공했을 때가 아니라
백엔드가 종료 상태를 확인했을 때 해결됩니다.

여러 호출자는 동일한 기본 중단 작업을 공유합니다. 첫 번째 호출자가
이를 생성하고, 후속 호출자가 참여합니다. `snapshot_on_stop=True`
요청이 스냅샷을 캡처하지 않는 중단에 참여(또는 관찰)하려고 하면,
샌드박스가 이미 중단 중이거나 이미 중단되었거나
일반 `stop()`이 이미 진행 중이기 때문에
`SnapshotOnStopConflictError`를 발생시키며, 아카이브 없이
조용히 완료되지 않습니다. 일반 중단은 항상 병합됩니다.

중단 성공 여부와 관계없이 샌드박스는 더 이상 사용할 수 없으므로
세션에서 등록 해제됩니다.
**매개변수**

* `snapshot_on_stop` (`bool`): True인 경우 종료 전에 설정된 마운트의 파일 시스템 스냅샷(FSS)을 캡처합니다. 결과 스냅샷 ID는 반환된 OperationRef가 해결된 후 `file_system_snapshot_id` 속성을 통해 확인할 수 있습니다. 샌드박스가 `file_system_snapshot` 마운트로 시작되었고 조직에서 FSS가 활성화되어 있어야 합니다. 스냅샷을 캡처하지 않을 중단이 이미 진행 중이면 `SnapshotOnStopConflictError`를 발생시킵니다.
* `graceful_shutdown_seconds` (`float`): 정상 종료까지 대기할 시간입니다. `snapshot_on_stop=True`인 경우 아카이브 후 파드 삭제 유예 기간이며, 스냅샷 *완료 후*에 적용되므로 클라이언트 데드라인이 아카이브 예산과 이 유예 기간을 모두 포함합니다. v1에서 `grace_period_seconds=0`은 즉시 종료를 의미합니다(백엔드 유예 대체 없음). 백엔드는 snapshot-on-stop의 경우 이 값을 300s로 제한합니다.
* `missing_ok` (`bool`): True인 경우 샌드박스가 존재하지 않을 때 SandboxNotFoundError를 억제합니다. `snapshot_on_stop=True`인 경우에도 플래그는 `allow_missing`으로 전송되며, 샌드박스가 없거나 서버가 해당 조합을 거부하면 `SnapshotOnStopConflictError`를 발생시키며 아카이브 없이 성공하지 않습니다.
* `wait_for_ready` (`bool`): `snapshot_on_stop`이 True인 경우 스냅샷이 READY(또는 FAILED)에 도달할 때까지 중단이 완료되기 전에 차단합니다. `snapshot_on_stop`이 False인 경우 무시됩니다.
* `request_id` (`str | None`): 스냅샷-on-stop 요청을 재시도 시 중복 제거하기 위한 선택적 클라이언트 제공 키입니다. `snapshot_on_stop`이 False인 경우 무시됩니다.

**반환값**

* `OperationRef[None]`: OperationRef\[None]: .result()를 사용하여 종료 상태까지 차단합니다.
* `OperationRef[None]`: 실패 시 SandboxError, 찾을 수 없는 경우 SandboxNotFoundError를 발생시킵니다.
* `OperationRef[None]`: (missing\_ok=True인 경우 제외).

**예시**

```python theme={"system"}
sb.stop().result()  # 터미널 상태(COMPLETED/FAILED)가 될 때까지 대기

# 이미 삭제된 경우 무시
sb.stop(missing_ok=True).result()

# stop 시 설정된 마운트의 스냅샷을 캡처한 후 ID를 조회합니다
sb.stop(snapshot_on_stop=True).result()
file_system_snapshot_id = sb.file_system_snapshot_id

# stop() 후 wait_until_complete()는 터미널 상태에서 해결됩니다
sb.stop()
sb.wait_until_complete().result()  # TERMINATING을 통해 폴링합니다
```

<h3 id="snapshot">
  snapshot
</h3>

```python theme={"system"}
snapshot(*, wait_for_ready: bool = True, request_id: str | None = None) -> OperationRef[str]
```

설정된 마운트의 파일 시스템 스냅샷(FSS)을 캡처합니다.

실행 중인 샌드박스에서 `file_system_snapshot`으로 설정된 디렉터리의
스냅샷을 생성하며, 샌드박스를 중지하지 않습니다. 샌드박스가 아직 시작되지 않았다면
먼저 시작합니다. 다음을 통해 스냅샷을 새 샌드박스에 복원하세요:
`Sandbox.run(file_system_snapshot=FileSystemSnapshotOptions(...,
file_system_snapshot_id=<id>))`.

샌드박스가 `file_system_snapshot` 마운트를 사용하여 시작되었고,
조직에서 FSS가 활성화되어 있어야 합니다.
**매개변수**

* `wait_for_ready` (`bool`): 스냅샷이 READY(또는 FAILED) 상태가 될 때까지 대기한 후 반환합니다. False이면 스냅샷이 생성되는 즉시 반환합니다(아직 CREATING 상태일 가능성이 높습니다).
* `request_id` (`str | None`): 재시도 시 중복 요청을 제거하기 위해 클라이언트가 제공하는 키입니다(선택 사항).

**반환값**

* `OperationRef[str]`: OperationRef\[str]: .result()를 사용하여 새 스냅샷의 ID가 반환될 때까지 대기(또는 await)하세요.
* `OperationRef[str]`: `Sandbox.get_snapshot(id)`를 호출하여 전체 레코드
* `OperationRef[str]`: (status, size, timestamps)를 조회하세요.

**예외**

* `SandboxSnapshotError`: 스냅샷 생성에 실패한 경우 발생합니다(조직에서 FSS가 활성화되지 않았을 때의 `NOT_SUPPORTED`, 할당량/크기 관련 오류 등은 하위 클래스를 참조하세요).

**예시**

```python theme={"system"}
with Sandbox.run(
    file_system_snapshot=FileSystemSnapshotOptions(mount_path="/workspace"),
) as sb:
    sb.exec(["sh", "-c", "echo hi > /workspace/note.txt"]).result()
    snapshot_id = sb.snapshot().result()
    # 필요한 경우 전체 레코드를 확인하세요:
    snap = Sandbox.get_snapshot(snapshot_id).result()
```

<h3 id="exec">
  exec
</h3>

```python theme={"system"}
exec(command: Sequence[str], *, cwd: str | None = None, check: bool = False, timeout_seconds: float | None = None, stdin: bool = False, container: str | None = None) -> Process
```

명령을 실행하고 Process를 즉시 반환합니다.

참고: 샌드박스가 아직 RUNNING 상태가 아니면, 이 방법은 먼저 해당 상태가 될 때까지 기다립니다.
timeout\_seconds 매개변수는 명령 실행에만 적용되며,
RUNNING 상태가 될 때까지의 초기 대기에는 적용되지 않습니다.
**매개변수**

* `command` (`Sequence[str]`): 실행할 명령과 인수
* `cwd` (`str | None`): 명령 실행을 위한 작업 디렉터리. 절대 경로여야 합니다. 지정된 경우, 명령이 셸 cd로 래핑됩니다.
* `check` (`bool`): True인 경우, 0이 아닌 반환 코드에서 SandboxExecutionError를 발생시킵니다.
* `timeout_seconds` (`float | None`): 명령 실행에 대한 timeout (샌드박스가 RUNNING 상태가 된 후). 샌드박스가 RUNNING 상태에 도달할 때까지 기다리는 시간은 포함되지 않습니다.
* `stdin` (`bool`): True인 경우, stdin 스트리밍을 활성화합니다. Process.stdin은 명령에 입력을 보낼 수 있는 StreamWriter가 됩니다. False(기본값)인 경우, stdin은 즉시 닫히고 Process.stdin은 None입니다.
* `container` (`str | None`): exec할 컨테이너 이름. 비어 있거나 None이면 기본 컨테이너를 대상으로 합니다.

**반환값**

* `Process`: 스트리밍 stdout/stderr가 있는 Process 핸들. .result()를 호출하여 블록
* `Process`: 최종 ProcessResult를 위해, 또는 실시간 출력을 위해 .stdout/.stderr를 반복합니다.
* `Process`: stdin=True인 경우, Process.stdin은 StreamWriter입니다.

**예외**

* `ValueError`: command가 비어 있거나 cwd가 유효하지 않은 경우 (비어 있거나 상대 경로)

**예시**

```python theme={"system"}
# 결과 직접 조회
process = sb.exec(["echo", "hello"])
result = process.result()
print(result.stdout)

# 작업 디렉터리 지정
result = sb.exec(["ls", "-la"], cwd="/app").result()

# 실시간 출력 스트림
process = sb.exec(["python", "script.py"])
for line in process.stdout:
    print(line)
result = process.result()

# stdin 스트리밍 사용
process = sb.exec(["cat"], stdin=True)
process.stdin.write(b"hello world").result()
process.stdin.close().result()
result = process.result()

# 비동기 사용
result = await sb.exec(["echo", "hello"])
```

<h3 id="shell">
  shell
</h3>

```python theme={"system"}
shell(command: Sequence[str] | None = None, *, width: int | None = None, height: int | None = None, container: str | None = None) -> TerminalSession
```

샌드박스에서 대화형 TTY 세션을 시작합니다.

대화형 터미널 사용에 최적화된 TerminalSession을 반환합니다:
원시 바이트 출력(디코딩/재인코딩 없음), 출력 버퍼링 없음,
완료를 기다리지 않는 stdin.
**매개변수**

* `command` (`Sequence[str] | None`): 실행할 셸 명령입니다. 기본값은 \["/bin/bash"]입니다. \["/bin/sh"] 또는 \["/usr/bin/python3"] 같은 시퀀스를 받습니다.
* `width` (`int | None`): 초기 터미널 너비(열 수)입니다.
* `height` (`int | None`): 초기 터미널 높이(행 수)입니다.
* `container` (`str | None`): TTY 세션의 컨테이너 이름입니다. 빈 값/None이면 기본 컨테이너를 대상으로 합니다.

**반환값**

* `TerminalSession`: .output (StreamReader\[bytes])을 제공하는 TerminalSession 핸들입니다.
* `TerminalSession`: .stdin (StreamWriter) 및 .resize(w, h)를 제공합니다.

**예외**

* `ValueError`: command가 명시적으로 비어 있는 경우 발생합니다.

**예시**

```python theme={"system"}
session = sandbox.shell(width=80, height=24)
session.stdin.writeline("echo hello").result()
for chunk in session.output:
    sys.stdout.buffer.write(chunk)
exit_code = session.wait()
```

<h3 id="read_file">
  read\_file
</h3>

```python theme={"system"}
read_file(filepath: str, *, timeout_seconds: float | None = None, container: str | None = None) -> OperationRef[bytes]
```

샌드박스에서 파일을 조회하고 OperationRef를 즉시 반환합니다.
**매개변수**

* `filepath` (`str`): 샌드박스 내 파일 경로
* `timeout_seconds` (`float | None`): 오퍼레이션의 timeout
* `container` (`str | None`): 읽어올 컨테이너입니다. 비어 있거나 None이면 기본 컨테이너를 대상으로 합니다.

**반환값**

* `OperationRef[bytes]`: OperationRef\[bytes]: .result()를 사용하면 블로킹 상태로 대기한 후 내용을 가져옵니다.

**동작:** 약 32 MiB 이하의 파일은 단일 단항 호출로 읽습니다. 그보다 큰 파일(최대 약 256 MiB)은 자동으로 스트리밍 읽기로 전환되며, Sandbox별로 처음 전환될 때 INFO 수준으로 한 번 로깅됩니다. 서버가 파일 크기를 보고하는 경우, 약 256 MiB를 초과하는 파일은 `CWSANDBOX_FILE_TOO_LARGE`와 함께 거부되므로 이러한 파일에는 `read_file_streaming`을 사용하세요. 어느 방식으로 읽든 전체 결과는 메모리에 유지됩니다. 클라이언트가 원격 파일 크기를 항상 미리 알 수 있는 것은 아니므로(예: 백엔드가 크기 정보가 포함된 `CWSANDBOX_FILE_TOO_LARGE` 대신 리소스 고갈로 크기 초과를 알리는 경우), 매우 큰 파일이 거부되지 않고 전체가 버퍼링될 수도 있습니다. 큰 파일은 `read_file_streaming`을 사용하여 점진적으로 처리하고 메모리 사용량을 제한하는 것이 좋습니다.

**예외**

* `SandboxFileError`: 파일이 서버 한도를 초과하고 서버가 파일 크기를 보고한 경우 `reason == CWSANDBOX_FILE_TOO_LARGE`와 함께 발생하며, 스트리밍으로 읽은 데이터가 파일 크기보다 작은 경우(읽기 전 크기와 비교하여 잘림 감지) `reason == CWSANDBOX_FILE_TRUNCATED`와 함께 발생합니다.
* `SandboxStreamBackpressureError`: 큰 파일 읽기가 스트리밍으로 전환된 상태에서 클라이언트가 읽는 속도보다 출력이 더 빠르게 생성될 때 발생합니다(SandboxExecutionError의 하위 클래스).

**예시**

```python theme={"system"}
data = sb.read_file("/output/result.txt").result()
```

<h3 id="write_file">
  write\_file
</h3>

```python theme={"system"}
write_file(filepath: str, contents: bytes, *, timeout_seconds: float | None = None, container: str | None = None) -> OperationRef[None]
```

샌드박스에 파일을 쓰고 OperationRef를 즉시 반환합니다.
**매개변수**

* `filepath` (`str`): 샌드박스 내 파일 경로
* `contents` (`bytes`): 바이트 형식의 파일 내용
* `timeout_seconds` (`float | None`): 오퍼레이션의 timeout
* `container` (`str | None`): 파일을 쓸 컨테이너입니다. 빈 값/None이면 기본 컨테이너를 대상으로 합니다.

**반환값**

* `OperationRef[None]`: OperationRef\[None]: 완료될 때까지 대기하려면 .result()를 사용하세요.

**동작:** 최대 약 32 MiB의 페이로드는 단일 단항 호출로 기록됩니다. 더 큰 페이로드(최대 약 256 MiB)는 자동으로 스트리밍 쓰기로 전환됩니다. Sandbox별로 이러한 전환이 처음 발생할 때 INFO 수준으로 한 번 로깅합니다. 약 256 MiB를 초과하는 페이로드는 거부됩니다. 이 경우 `write_file_streaming`을 사용하세요.

**예외**

* `SandboxFileError`: 페이로드가 서버 한도를 초과하면 `reason == CWSANDBOX_FILE_TOO_LARGE`로 발생하며, 스트리밍 쓰기가 스트림 중간에 실패하여 불완전한 파일이 남아 있을 수 있는 경우에는 해당 reason 없이 발생합니다.
* `SandboxStreamBackpressureError`: 대용량 쓰기가 스트리밍으로 전환되고 소스가 전송 가능한 속도보다 빠르게 데이터를 생성할 때 발생합니다(SandboxExecutionError의 하위 클래스).

**예시**

```python theme={"system"}
sb.write_file("/input/data.txt", b"content").result()
```

<h3 id="write_file_streaming">
  write\_file\_streaming
</h3>

```python theme={"system"}
write_file_streaming(filepath: str, source: bytes | Iterable[bytes] | AsyncIterable[bytes], *, timeout_seconds: float | None = None, container: str | None = None) -> OperationRef[None]
```

전체 페이로드를 메모리에 올리지 않고 파일을 샌드박스로 스트리밍합니다.

페이로드가 대략
32 MiB보다 크거나 데이터가 이미 이터레이터(파일 핸들,
제너레이터, 비동기 생산자)인 경우 `write_file` 대신 이 방법을 사용하세요.
**매개변수**

* `filepath` (`str`): 샌드박스 내부의 절대 경로입니다.
* `source` (`bytes | Iterable[bytes] | AsyncIterable[bytes]`): `bytes`, 동기 `Iterable[bytes]` 또는 `AsyncIterable[bytes]` 형태의 페이로드입니다. 입력은 전송 전에 프레임 제한에 맞는 청크로 분할됩니다. 생성되는 항목은 `bytes`, `bytearray` 또는 `memoryview`여야 하며, 그 외의 유형은 `TypeError`를 발생시킵니다.
* `timeout_seconds` (`float | None`): 스트리밍 쓰기의 실제 경과 시간 기준 timeout입니다.

**반환값**

* `OperationRef[None]`: `OperationRef[None]`: 완료될 때까지 대기하려면 `.result()`를 호출하세요.

**예외**

* `SandboxStreamBackpressureError`: 소스가 전송 속도보다 빠르게 데이터를 생성하여 스트림이 조기에 종료되는 경우 발생합니다. 속도를 조절할 수 있는 소스에서 데이터를 생성하거나 대용량 업로드를 미리 청크로 분할하세요. 자세한 지침은 해당 예외의 독스트링을 참조하세요.

**주의 사항:** 대상에 직접 기록합니다(임시 파일 생성 후 이름 변경 방식이 아님). 스트리밍 도중 취소하거나 전송 오류가 발생하면 불완전한 파일이 남을 수 있습니다. 또한 샌드박스가 다시 시작되면 스트리밍 전송은 유지되지 않습니다. 동기 소스(예: `open(...)`의 파일 핸들)는 작업자 스레드에서 읽으므로 블로킹 `read`가 SDK의 이벤트 루프를 멈추지 않습니다. 비동기 소스는 직접 await합니다. 둘 다 사용할 수 있으므로 데이터에 더 자연스러운 방식을 선택하세요.

<h3 id="read_file_streaming">
  read\_file\_streaming
</h3>

```python theme={"system"}
read_file_streaming(filepath: str, *, timeout_seconds: float | None = None, container: str | None = None) -> StreamReader[bytes]
```

전체 페이로드를 버퍼링하지 않고 샌드박스의 파일을 청크 단위로 스트리밍합니다.

약 32 MiB보다 큰 파일이나,
파일을 점진적으로 처리하려는 경우(디스크에 쓰기,
즉시 해시 계산, 줄 단위 파싱)에는 `read_file`보다 이 방법을 사용하세요.

대용량 파일의 경우 SDK는 읽기 *전에* 파일 크기를 캡처하고,
스트림이 종료되면 최소한 그만큼의 바이트가
전달되었는지 검증합니다. 전달된 바이트가 더 적으면 이터레이터가
`CWSANDBOX_FILE_TRUNCATED` 사유로 `SandboxFileError`를 발생시켜,
호출자가 부분 파일을 처리하는 대신 오류 없이 발생한
불완전한 읽기를 감지할 수 있도록 합니다. (읽기 전 크기를 사용하므로
읽는 동안 내용이 추가된 파일을 잘린 파일로
오인하지 않습니다.) 오류 없이 파일이 잘리는 현상이 발생하지 않는
작은 파일에서는 이 검사를 건너뛰며, 크기를 확인할 수 없는 경우에는
최선의 노력으로 수행합니다.

루프에서 파일 스트리밍 속도보다 느리게 청크를 읽으면(예: 반복 사이에
시간이 오래 걸리는 작업을 수행하는 경우), 읽기가
`SandboxStreamBackpressureError`와 함께 조기에 종료될 수 있습니다. 신속하게 반복하고 시간이 오래 걸리는 작업은
읽기 루프 밖으로 옮기세요. 지침은 해당 예외의 독스트링을 참조하세요.
**매개변수**

* `filepath` (`str`): 샌드박스 내부의 절대 경로입니다.
* `timeout_seconds` (`float | None`): 스트리밍 읽기의 실제 경과 시간 기준 timeout입니다.

**반환값**

* `StreamReader[bytes]`: 청크를 순서대로 생성하는 `StreamReader[bytes]`입니다. 파일 끝은
* `StreamReader[bytes]`: 이터레이터의 정상적인 소진으로 표시됩니다. 오류(파일 없음,
* `StreamReader[bytes]`: 권한 거부, 파일 잘림, 지나치게 느린 읽기)는
* `StreamReader[bytes]`: 소비자가 해당 지점을 지나 반복할 때 다시 발생합니다.

**예시**

```python theme={"system"}
with contextlib.closing(sb.read_file_streaming("/data/big.bin")) as reader:
    with open("local.bin", "wb") as f:
        for chunk in reader:
            f.write(chunk)
```

**주의 사항:** 스트리밍 전송은 샌드박스가 재시작되면 유지되지 않습니다. 긴 전송 도중 재시작이 발생하면 스트림 중간에 실패합니다. 호출자는 리더를 끝까지 순회하거나 리더의 `close()`를 호출해야 합니다. SDK는 가비지 컬렉션 시 백그라운드 작업을 취소하는 종료 처리기를 설치하지만, 명시적으로 닫으면 리소스를 더 빨리 해제할 수 있습니다. 일시적인 데이터 급증을 완화하고 역압을 적용하기 위해 제한된 양의 출력을 루프보다 앞서 버퍼링하지만, 이는 엄격한 메모리 상한이 아닙니다. 루프 처리가 뒤처지는 정도에 따라 상주 메모리는 계속 증가합니다. 조회 루프의 처리 시간을 최소화하고 청크별로 수행하는 느린 작업은 루프 밖으로 옮기세요(`examples/large_file_streaming.py` 참조).

<h3 id="stream_logs">
  stream\_logs
</h3>

```python theme={"system"}
stream_logs(*, follow: bool = False, tail_lines: int | None = None, since_time: datetime | None = None, timestamps: bool = False, timeout_seconds: float | None = None, container: str | None = None) -> StreamReader[str]
```

샌드박스의 메인 프로세스에서 로그를 스트리밍합니다.

샌드박스의 **메인 명령**에서 stdout/stderr를 스트리밍합니다. 이는
`Sandbox.run()`에 전달된 진입점(또는 기본 셸 트랩 기반
keep-alive)입니다. `exec()`로 시작한 명령의 출력은 **포함되지 않습니다**.
해당 출력에는 `Process.stdout`/`Process.stderr`를 사용하세요.

.. note::

기본 keep-alive 명령으로 생성된 샌드박스는
로그 출력을 생성하지 않습니다. 여기서 로그를 보려면
`Sandbox.run()`을 호출할 때 stdout/stderr에 쓰는 명령을 전달하세요.

로그 줄을 string으로 산출하는 StreamReader를 반환합니다. 이 방법은
즉시 반환되며, StreamReader를 반복 순회하면
데이터가 도착할 때까지 차단됩니다.
**매개변수**

* `follow` (`bool`): True이면 새 로그를 계속 스트리밍합니다(`tail -f`와 유사). False이면 실행 중인 샌드박스의 기존 로그를 스트리밍하고 종료합니다. 중단된 샌드박스는 `StreamLogs`를 거부합니다.
* `tail_lines` (`int | None`): 조회할 가장 최근 줄 수입니다. None이면 사용 가능한 모든 줄을 반환합니다.
* `since_time` (`datetime | None`): 이 타임스탬프 이후의 로그만 반환합니다. 시간대 정보가 있어야 하며, 시간대 정보가 없는 datetime은 `ValueError`를 발생시킵니다.
* `timestamps` (`bool`): True이면 각 줄에 서버의 ISO 8601 타임스탬프를 접두사로 추가합니다.
* `timeout_seconds` (`float | None`): gRPC 호출의 클라이언트 측 제한 시간입니다. 기본값은 `follow=False`일 때 `request_timeout_seconds`, `follow=True`일 때 `None`(timeout 없음)입니다.
* `container` (`str | None`): 로그를 스트리밍할 컨테이너입니다. 비어 있거나 None이면 기본 컨테이너를 대상으로 합니다.

**반환값**

* `StreamReader[str]`: 로그 줄을 string으로 산출하는 StreamReader입니다. 동기적으로 반복 순회하려면
* `StreamReader[str]`: `for line in reader`를 사용하고, 비동기적으로 반복 순회하려면
* `StreamReader[str]`: `async for line in reader`를 사용하세요.

**예외**

* `SandboxNotRunningError`: `follow=True`이고 샌드박스가 중단된 경우 발생합니다.
* `SandboxError`: 로그 스트림에서 오류가 발생한 경우 발생합니다.

**예시**

```python theme={"system"}
# 일회성: 최근 로그 조회
for line in sandbox.stream_logs(tail_lines=100):
    print(line, end="")

# 추적 모드: 지속적으로 스트리밍
for line in sandbox.stream_logs(follow=True):
    print(line, end="")

# 비동기 사용
async for line in sandbox.stream_logs(follow=True):
    print(line, end="")
```
