> ## 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.

# 샌드박스 TypeScript 클라이언트

> 샌드박스를 생성하고 명령어를 실행하는 방법을 알아보고, TypeScript 소프트웨어 개발 키트(SDK) API를 찾아보세요.

`@coreweave/cwsandbox` TypeScript 클라이언트로 CoreWeave 샌드박스를 생성하고 관리할 수 있습니다. 이 가이드에서는 클라이언트를 생성하고, 샌드박스에서 명령어를 실행하고, SDK 오류를 처리하는 방법을 설명합니다. 샌드박스 TypeScript 예시와 API 참조는 버전 1.0.0을 기준으로 합니다. 가이드를 따라 하려면 이 버전을 설치하세요.

## 사전 요구 사항

Node.js 22 이상과 ECMAScript 모듈(ESM) 프로젝트를 사용하세요. 예시를 `tsx`로 실행하려면 `.mts` 파일로 저장하세요.

[사용자 인증 정보 선택 및 가져오기](https://docs.coreweave.com/ko/products/sandboxes/placement.md#choose-and-get-credentials)에서 사용할 사용자 인증 정보를 선택하세요. 예시에서는 서버리스 용량을 사용합니다. CoreWeave Kubernetes Service(CKS)에 배치하려면 [러너를 활성화](https://docs.coreweave.com/ko/products/sandboxes/get-started-cks.md)하고, `runnerIds` 배열이 비어 있지 않은 CoreWeave API 액세스 토큰을 사용하세요.

SDK를 설치하세요.

```bash theme={"system"}
npm install @coreweave/cwsandbox@1.0.0
```

## 클라이언트 생성

사용하는 사용자 인증 정보에 맞는 진입점을 선택하세요. 두 팩토리 모두 [`SandboxClient`](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/client#sandboxclient)를 반환합니다. 루트 `@coreweave/cwsandbox` 진입점은 유형, 상수, 오류만 내보내므로 클라이언트는 `/wandb` 또는 `/node`를 통해 생성하세요.

선택한 탭의 코드를 다른 예시 파일과 같은 위치에 `sandbox-client.mts` 파일로 저장하세요. 이 코드는 인증 방식을 선택하고 클라이언트를 내보냅니다. 사용자 인증 정보는 코드가 아닌 환경 변수에 보관됩니다.

> [tab] Forge API 키
>
> `[WANDB-API-KEY]`를 Forge API 키로 바꾸세요.
>
> ```bash theme={"system"}
> export WANDB_API_KEY="[WANDB-API-KEY]"
> ```
>
> ```typescript title="sandbox-client.mts" theme={"system"}
> import { createSandboxClientFromEnv } from "@coreweave/cwsandbox/wandb";
>
> export const client = createSandboxClientFromEnv();
> ```
>
> Forge 팀을 지정하려면 `WANDB_ENTITY`를 설정하세요. 옵션을 명시적으로 지정하는 방법은 [Forge 클라이언트 팩토리](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/wandb.md)를 참조하세요.

> [tab] CoreWeave API 액세스 토큰
>
> `[API-ACCESS-TOKEN]`을 토큰으로 바꾸세요.
>
> ```bash theme={"system"}
> export CWSANDBOX_API_KEY="[API-ACCESS-TOKEN]"
> ```
>
> ```typescript title="sandbox-client.mts" theme={"system"}
> import { createSandboxClientFromEnv } from "@coreweave/cwsandbox/node";
>
> export const client = createSandboxClientFromEnv();
> ```
>
> 이 팩토리는 `CWSANDBOX_BASE_URL`도 읽으며, 기본값은 `https://api.cwsandbox.com` 입니다. 옵션을 명시적으로 지정하는 방법은 [Node 클라이언트 팩토리](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/node.md)를 참조하세요.

## 명령어 실행

callback이 끝나면 함께 중지되어야 하는 작업에는 `withSandbox()`를 사용하세요. 이 함수는 샌드박스가 준비 상태가 될 때까지 기다렸다가 callback을 호출하며, callback이 반환되거나 예외를 던지면 샌드박스를 중지합니다.

```typescript title="hello.mts" theme={"system"}
import { client } from "./sandbox-client.mjs";

const result = await client.withSandbox(
  async (sandbox) => sandbox.commands.run(["echo", "Hello!"]),
  {
    containerImage: "python:3.11",
    resources: { cpu: "1", memory: "1Gi" },
  },
);

console.log(result.stdout);
```

스크립트를 실행하세요.

```bash theme={"system"}
npx --yes --package=tsx tsx hello.mts
```

스크립트는 `Hello!`를 출력한 후 샌드박스를 중지합니다.

`tsx`로 실행하거나 TypeScript로 컴파일하면 `./sandbox-client.mjs` 임포트는 로컬 `sandbox-client.mts` 파일로 해석됩니다.

`commands.run()`은 표준 출력(stdout)과 표준 오류(stderr)를 버퍼링한 뒤 `exitCode`가 포함된 [`ProcessResult`](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/commands#processresult)를 반환합니다. 출력을 스트리밍하려면 `commands.start()`를 사용하세요.

여러 오퍼레이션에서 샌드박스를 계속 사용하려면 `client.create()`로 생성한 다음 `finally` 블록에서 중지하세요. 자세한 내용은 [샌드박스 라이프사이클 레퍼런스](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/sandboxes.md#sandbox)를 참조하세요.

## 오류 처리

`isCWSandboxError()`를 사용해 알 수 없는 오류의 타입을 좁힌 다음 `code`를 확인하세요.

```typescript theme={"system"}
import { isCWSandboxError } from "@coreweave/cwsandbox";
import { client } from "./sandbox-client.mjs";

try {
  await client.withSandbox(async (sandbox) => {
    await sandbox.commands.run(["false"], { check: true });
  });
} catch (error) {
  if (isCWSandboxError(error)) {
    console.error(error.code, error.message);
  } else {
    throw error;
  }
}
```

`check: true`를 지정하면 명령어가 0이 아닌 종료 코드로 끝날 때 `CWSandboxExecutionError` 예외가 발생합니다. 오류 계층 구조와 사용 가능한 메타데이터는 [오류](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/errors.md)를 참조하세요.

## API 레퍼런스

이 레퍼런스 문서는 메서드 오버로드, 매개변수 및 반환 유형, 선택적 필드, 상속된 유형을 포함하여 게시된 선언을 그대로 유지합니다. SDK 주석에는 검토를 거친 수정 사항이 반영되어 있습니다.

| 레퍼런스 | 내용 |
| - | - |
| [클라이언트 및 검색](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/client.md) | 샌드박스를 생성, 재연결, 나열, 정리하고 템플릿 또는 Compose 파일에서 시작합니다. |
| [샌드박스 및 라이프사이클](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/sandboxes.md) | 샌드박스 핸들, 시작 옵션, 스냅샷, 라이프사이클 상태를 다룹니다. |
| [명령어 및 터미널](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/commands.md) | 명령어 실행, 프로세스 핸들, 표준 입력(stdin), 대화형 터미널을 다룹니다. |
| [파일](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/files.md) | 버퍼 방식 및 스트리밍 방식의 파일 작업과 마운트된 파일을 다룹니다. |
| [로그](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/logs.md) | 샌드박스 로그를 조회하고 스트리밍합니다. |
| [네트워크 및 서비스](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/network.md) | 네트워크 규칙, 서비스, 엔드포인트를 다룹니다. |
| [리소스 및 시크릿](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/resources.md) | 리소스 요청량 및 제한, 시크릿 입력을 다룹니다. |
| [요청 옵션 및 기본값](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/common.md) | timeout, 취소, 데이터 영역 모드, 기본 상수를 다룹니다. |
| [오류](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/errors.md) | 오류 클래스, 코드, 백엔드 사유 상수를 다룹니다. |
| [Node 클라이언트 팩토리](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/node.md) | CoreWeave 토큰 인증과 클라이언트 생성을 다룹니다. |
| [Forge 클라이언트 팩토리](https://docs.coreweave.com/ko/products/sandboxes/typescript-client/ref/wandb.md) | Forge 인증과 팀 선택을 다룹니다. |

Compose 예시는 [TypeScript에서 샌드박스 생성하기](https://docs.coreweave.com/ko/products/sandboxes/create-from-file.md#create-a-sandbox-from-typescript)를 참조하세요.
