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

# 샌드박스에서 OpenCode 실행하기

> W&B Serverless Inference 또는 다른 모델 공급자를 사용해 샌드박스에서 OpenCode를 실행합니다.

Run OpenCode against a repository in a CoreWeave sandbox. Send a task from your
terminal, check the resulting files, and save the workspace for later. The agent
process, workspace, and commands run in the sandbox. Model requests go to your
configured provider.

## Prerequisites

Before you begin, you need the following:

* 샌드박스 액세스에 사용할 [W\&B API 키](https://forge.coreweave.com/settings#apikeys). 이 예시에서는
  W\&B 인증을 사용합니다.
* W\&B Serverless Inference 또는 다른
  OpenCode 공급자를 통한 모델 액세스 권한. 공급자 액세스 및
  결제는 샌드박스 액세스와 별도로 관리됩니다.
* 공개 저장소 URL. 비공개 저장소를 사용하려면 샌드박스 내부에
  Git 자격 증명이 필요합니다.
* [설치 안내](https://github.com/coreweave/cws-agent#install)에 따라
  설치한 `cws-agent`.

로컬 터미널에서 `[WANDB-API-KEY]`를 전체 W\&B API 키로 바꾸세요.

```bash theme={"system"}
export WANDB_API_KEY="[WANDB-API-KEY]"
unset CWSANDBOX_API_KEY
```

`cws-agent`가 W\&B 인증을 선택하게 하려면 `CWSANDBOX_API_KEY` 설정을 해제하세요.

## Launch OpenCode with cws-agent

`cws-agent`를 사용해 샌드박스에 OpenCode를 설치하고, 저장소를
`/workspace/project` 디렉터리에 클론한 다음,
[파일 시스템 스냅샷](/products/sandboxes/serverless/file-system-snapshots)에 사용할 스냅샷 마운트를 설정하세요.

Choose one of the following provider options. Replace `[SANDBOX-NAME]` with a
session name containing 1 to 40 lowercase letters, digits, or hyphens. Start the
name with a letter or digit. Replace `[REPOSITORY-URL]` with your public repository URL.

### Use W\&B Serverless Inference (recommended)

W\&B Serverless Inference is the preferred provider for this guide. You can use
it to access hosted open models. You can use any model and provider supported by
OpenCode instead. Follow
[Use another model provider](#use-another-model-provider).

Complete the [W\&B Serverless Inference prerequisites](/products/inference/serverless/api-reference#prerequisites),
including a W\&B project, and check your available
[inference credits](/products/inference/serverless/usage-limits).
This example selects GLM 5.2 explicitly:

```bash theme={"system"}
cws-agent launch [SANDBOX-NAME] --agent opencode \
  --repo-url [REPOSITORY-URL] --lifetime 2h \
  --wandb --wandb-model zai-org/GLM-5.2 \
  --permission-mode native --detach
```

`--wandb` 프리셋은 W\&B의 추론 엔드포인트를 설정하고, `WANDB_API_KEY`를
샌드박스로 전달하며, OpenCode가 해당 공급자만 사용하도록 제한합니다. 에이전트는
이 키 하나로 추론과 샌드박스에 모두 액세스할 수 있습니다. 다른 W\&B 모델을
사용하려면 `zai-org/GLM-5.2`를
[사용 가능한 모델](/ko/products/inference/serverless/models) 목록에 있는 ID로 바꾸세요.

### Use another model provider

To use another provider, omit `--wandb` and `--wandb-model` when you create the
sandbox. Export that provider's API key locally. For example, choose one of
these alternatives and replace the key placeholder:

<Tabs>
  <Tab title="Anthropic">
    ```bash theme={"system"}
    export ANTHROPIC_API_KEY="[ANTHROPIC-API-KEY]"
    ```
  </Tab>

  <Tab title="OpenAI">
    ```bash theme={"system"}
    export OPENAI_API_KEY="[OPENAI-API-KEY]"
    ```
  </Tab>
</Tabs>

Replace `[PROVIDER-ID]/[MODEL-ID]` in both fields with your OpenCode model
identifier, using the `anthropic/` or `openai/` provider prefix as appropriate.
The `small_model` field selects the model for lightweight tasks such as title
generation. See [OpenCode models](https://opencode.ai/docs/models/).

```bash theme={"system"}
export OPENCODE_CONFIG_CONTENT='{"model":"[PROVIDER-ID]/[MODEL-ID]","small_model":"[PROVIDER-ID]/[MODEL-ID]"}'
cws-agent launch [SANDBOX-NAME] --agent opencode \
  --repo-url [REPOSITORY-URL] --lifetime 2h \
  --env-passthrough OPENCODE_CONFIG_CONTENT \
  --permission-mode native --detach
```

If they're set, `cws-agent` forwards `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`.
For providers whose keys aren't forwarded automatically, follow their
[OpenCode provider configuration](https://opencode.ai/docs/providers/) and use
`--env-passthrough [VARIABLE-NAME]` for additional environment variables.

Both launch options print `session ready.` after setup. `--detach` leaves the
sandbox running without opening the terminal interface or importing local
skills and Model Context Protocol (MCP) configuration. The 2-hour lifetime is a
wall-clock limit, including setup. Stop compute when you finish.

## Run a task and check the result

From your local terminal, ask OpenCode to write and read a file:

```bash theme={"system"}
cws-agent run [SANDBOX-NAME] \
  'Create sandbox-proof.txt in the current directory containing exactly Hello from CoreWeave followed by a newline, then read it back. Do not commit or push anything.' \
  --permission-mode native
```

This runs OpenCode without an interactive terminal. `--permission-mode native`
keeps OpenCode's configured permissions. Without it, `cws-agent` defaults to
accepting approval requests. If your OpenCode policy requires approval for the
task, use an interactive session to approve it. See
[OpenCode permissions](https://opencode.ai/docs/permissions/).

Check the actual file independently of the agent's response:

```bash theme={"system"}
cws-agent exec [SANDBOX-NAME] 'cat /workspace/project/sandbox-proof.txt'
```

The output should be `Hello from CoreWeave`. Before you stop compute, retrieve
a local copy:

```bash theme={"system"}
cws-agent exec [SANDBOX-NAME] 'cat /workspace/project/sandbox-proof.txt' > sandbox-proof.txt
```

### Optional: Work interactively

From an interactive terminal on macOS or Linux, open OpenCode in the
same workspace:

```bash theme={"system"}
cws-agent connect [SANDBOX-NAME] --permission-mode native --no-config-sync
```

The `--no-config-sync` flag skips local skills and MCP imports. Send prompts and
approve actions in OpenCode, then use `/exit` to return to your local terminal.
When you exit OpenCode, the sandbox continues to run. Repeat the connection
command to open OpenCode again. It doesn't automatically select a previous conversation.
For conversation history and resume commands, see
[`cws-agent` sessions](https://github.com/coreweave/cws-agent/blob/main/docs/sessions.md).

## Save, stop, and restore

After the agent finishes, snapshot the workspace and stop compute:

```bash theme={"system"}
cws-agent down [SANDBOX-NAME]
```

`down` saves the `/workspace` directory before stopping the sandbox. If the snapshot fails,
the sandbox remains running. Inspect the error and retry after resolving it.
To stop without waiting for an explicit snapshot, run:

```bash theme={"system"}
cws-agent down [SANDBOX-NAME] --no-snapshot
```

Don't rely on this command to save changes. Copy results elsewhere or confirm
a completed snapshot before stopping. Restore requires a completed snapshot.

To return to a workspace saved with W\&B inference, make sure `WANDB_API_KEY` is
still exported in your local terminal, then run:

```bash theme={"system"}
cws-agent restore [SANDBOX-NAME] --wandb --wandb-model zai-org/GLM-5.2 --lifetime 2h --no-config-sync
```

Use the same `--wandb-model` value you launched with. If you omit it while using
`--wandb`, restore selects the preset's default model.

For another provider, re-export its key and `OPENCODE_CONFIG_CONTENT`, then run:

```bash theme={"system"}
cws-agent restore [SANDBOX-NAME] --env-passthrough OPENCODE_CONFIG_CONTENT --lifetime 2h --no-config-sync
```

Restore creates a new sandbox from the saved workspace. Supply environment-only
credentials again. Snapshots can contain saved OpenCode logins
and conversation data, but they don't preserve running processes.

Run the file check again to confirm the `sandbox-proof.txt` file survived. Continue with
`cws-agent run` or the interactive connection command. Stop the restored sandbox
with `cws-agent down` when you finish.

## Troubleshoot

If setup or a task fails, use the following checks:

* 샌드박스 인증에 실패하는 경우: 전체 W\&B API 키와 샌드박스
  액세스 권한을 확인하세요.
* W\&B 모델 요청이 실패하는 경우: 추론 액세스 권한, 크레딧, 모델
  ID를 확인하세요. 샌드박스 액세스 권한이 있다고 해서 추론 액세스 권한이 부여되지는 않습니다.
* 다른 공급자를 사용할 수 없는 경우: `--wandb` 없이 새 세션을 시작하세요.
  W\&B 프리셋은 워크스페이스에 저장되므로 복원할 때 `--wandb`를 생략해도
  프리셋은 제거되지 않습니다. 기존 워크스페이스는
  [W\&B 프리셋 설정](https://github.com/coreweave/cws-agent/blob/main/docs/opencode.md#resume-and-restore)을 참조하세요.
* 헤드리스 작업에 승인이 필요한 경우: 대화형으로 연결해 OpenCode의
  승인 프롬프트에 응답한 후 계속 진행하세요.

## Next steps

For more information, see these guides:

* [Run agents on CoreWeave sandboxes](.) explains agent
  execution models and workspace lifetimes.
* [OpenCode configuration](https://opencode.ai/docs/config/) covers model,
  provider, and project settings.
* [Use the Sandbox SDK](../client/guides/execution) explains how
  to manage command execution directly from your application.
