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

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

> CoreWeave 샌드박스에서 Cursor CLI를 대화형으로 실행하거나 코딩 작업을 자동화하세요.

Run the Cursor command-line interface (CLI) against a repository in a CoreWeave
sandbox. Attach your terminal for interactive work, or run a prompt through the
Sandbox software development kit (SDK) and collect the result. The CLI process,
workspace, and commands run in the sandbox. Model requests go to Cursor.

Cursor also supports [Self-Hosted Machines](https://cursor.com/docs/cloud-agent/self-hosted),
where Cursor's cloud runs the agent loop and a separate worker executes tool calls.

## Prerequisites

Before you begin, you need the following:

* 샌드박스 액세스 권한이 있는 [W\&B API 키](https://forge.coreweave.com/settings#apikeys)

- A [Cursor user API key](https://cursor.com/docs/cli/reference/authentication#api-key-authentication)
  and access to a model supported by Cursor CLI.
- A public repository URL. Private repositories require Git credentials inside
  the sandbox.
- Outbound connectivity to Cursor, its download host, and your Git host.

In your local terminal, set the sandbox credential you want to use:

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

`CWSANDBOX_API_KEY` 설정을 해제하면 `cws-agent`가 W\&B 인증을 선택합니다.

Cursor reads `CURSOR_API_KEY` inside the sandbox. Cursor can send
prompts, file contents, and tool output to its service. Use a repository and
credentials appropriate for the task.

## Run Cursor CLI with cws-agent

Use `cws-agent` to create a sandbox, install Cursor, and attach your terminal.
Interactive attachment requires an interactive terminal (TTY) on macOS, Linux,
or Windows Subsystem for Linux (WSL). Native Windows terminals aren't supported.

Export your Cursor key locally. `cws-agent` forwards it into the sandbox's
environment:

```bash theme={"system"}
export CURSOR_API_KEY="[CURSOR-API-KEY]"
```

1. Follow the [`cws-agent` installation instructions](https://github.com/coreweave/cws-agent#install).

2. Replace `[SANDBOX-NAME]` with a session name containing 1 to 40 lowercase
   letters, digits, or hyphens, starting with a letter or digit. Replace
   `[REPOSITORY-URL]` with your repository URL:

   ```bash theme={"system"}
   cws-agent launch [SANDBOX-NAME] --agent cursor --repo-url [REPOSITORY-URL] --lifetime 2h --permission-mode native --no-config-sync
   ```

   Cursor opens in `/workspace/project`. If a workspace trust prompt appears,
   accept it. `--permission-mode native` retains Cursor's approval settings.
   `cws-agent` otherwise uses `--force`. `--no-config-sync` skips importing your
   local skills and Model Context Protocol (MCP) configuration.

3. Ask Cursor to create a file you can retrieve:

   ```text theme={"system"}
   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.
   ```

   Approve any prompts for the task. Exit Cursor with `/exit`.
   In your local terminal, read the file:

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

   The output should be `Hello from CoreWeave`. Exiting Cursor leaves the
   sandbox running.

4. After exiting all Cursor sessions in the sandbox, remove Cursor's leftover
   `worker.sock` socket files, save the workspace, and stop compute:

   ```bash theme={"system"}
   cws-agent exec [SANDBOX-NAME] 'find /workspace/home/.cursor/projects -type s -name worker.sock -delete'
   cws-agent down [SANDBOX-NAME]
   ```

   The cleanup removes socket files that can block snapshot creation. `down`
   takes a snapshot before stopping the sandbox.
   If snapshot creation fails, the sandbox stays running. Resolve the error and
   retry `down` before restoring.

5. To return to the saved workspace, keep `CURSOR_API_KEY` exported locally and run:

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

   Ask Cursor to read the `sandbox-proof.txt` file to verify that it was restored.
   When finished, exit Cursor and repeat the cleanup and `down` commands.

### Run an unattended prompt

Choose a new session name. In your local terminal, launch with `--detach` to skip
terminal attachment, then send a prompt:

```bash theme={"system"}
cws-agent launch [SANDBOX-NAME] --agent cursor --repo-url [REPOSITORY-URL] --lifetime 2h --permission-mode native --no-config-sync --detach
cws-agent run [SANDBOX-NAME] 'Create sandbox-proof.txt containing exactly Hello from CoreWeave followed by a newline, then read it back. Do not commit or push anything.'
```

`cws-agent run` passes Cursor's `--force` flag by default so the headless task can
write files without interactive approval. Cursor retains explicit deny rules.

To attach your terminal to the running session, run:

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

When finished, exit Cursor if attached, read the result with `cws-agent exec`,
then clean up the sockets and save with `cws-agent down` as shown in
[Run Cursor CLI with cws-agent](#run-cursor-cli-with-cws-agent).

## Run a task with the Sandbox SDK

Use the Sandbox SDK to manage a task directly. This
path creates a separate sandbox, runs Cursor in print mode, retrieves the file,
and stops the sandbox in a cleanup block. It doesn't configure snapshots or
require `cws-agent`.

### Choose how to supply the Cursor key

Both scripts take an authentication mode as their first argument:

| 모드 | 샌드박스 자격 증명 | Cursor 자격 증명 |
| - | - | - |
| `wandb` | `WANDB_API_KEY` | 서버에서 확인하는 W\&B 팀 시크릿 |

W\&B 시크릿 주입을 사용하려면 W\&B 인증과 서버리스 배치가 필요합니다.

W\&B Admin에게 [Cursor 키를 팀 시크릿으로 추가](/ko/products/wandb/platform/secrets#add-a-secret)해 달라고 요청하세요.
로컬 터미널에서 `[WANDB-TEAM]`은 팀 이름으로,
`[CURSOR-SECRET-NAME]`은 시크릿 이름으로 바꾸세요.

```bash theme={"system"}
export WANDB_ENTITY="[WANDB-TEAM]"
export CURSOR_SECRET_NAME="[CURSOR-SECRET-NAME]"
```

W\&B API 키에 해당 팀에 대한 액세스 권한이 있어야 합니다. 스크립트는 지정한
시크릿을 샌드박스 내부의 `CURSOR_API_KEY`에 매핑합니다.
[W\&B 시크릿 사용](/ko/products/sandboxes/serverless/secrets)을 참조하세요.

### Install a client

Choose a language and install the client locally:

<Tabs>
  <Tab title="Python">
    Use Python 3.11 or later and `uv`. In a new project directory, run:

    ```bash theme={"system"}
    uv init --python 3.11
    uv add 'cwsandbox[wandb]==1.14.2'
    ```
  </Tab>

  <Tab title="TypeScript">
    Use Node.js 22 or later. In your project directory, run:

    ```bash theme={"system"}
    npm install @coreweave/cwsandbox@0.5.0-beta.0 tsx
    ```
  </Tab>
</Tabs>

### Create, run, and clean up

Save the script for your language using the filename shown. Each script installs
Cursor, clones the repository passed on the command line, and asks Cursor to
write the `sandbox-proof.txt` file.

The `--print`, `--force`, and `--trust` flags enable non-interactive output,
permit file changes, and trust the workspace. Use this
example only with a repository you trust. See
[Cursor headless mode](https://cursor.com/docs/cli/headless).

<Tabs>
  <Tab title="Python">
    ```python title="run_cursor_sandbox.py" theme={"system"}
    import os
    import sys

    from cwsandbox import AuthStrategy, Sandbox, Secret

    if len(sys.argv) != 3 or sys.argv[1] not in ("wandb", "coreweave"):
        raise SystemExit("Pass wandb or coreweave, then a repository URL.")

    mode, repository = sys.argv[1:]
    if mode == "wandb":
        auth = AuthStrategy.WANDB
        credentials = {"secrets": [Secret(
            store="wandb", name=os.environ["CURSOR_SECRET_NAME"],
            env_var="CURSOR_API_KEY",
        )]}
    else:
        auth = AuthStrategy.COREWEAVE_API_KEY
        credentials = {
            "environment_variables": {"CURSOR_API_KEY": os.environ["CURSOR_API_KEY"]},
        }

    sandbox = Sandbox.run(
        auth=auth,
        placement_mode="serverless",
        container_image="node:22-bookworm",
        resources={"cpu": "2", "memory": "4Gi"},
        max_lifetime_seconds=2 * 3600,
        **credentials,
    )
    try:
        sandbox.wait()
        commands = [
            ["bash", "-o", "pipefail", "-ec", "curl -fsSL https://cursor.com/install | bash"],
            ["mkdir", "-p", "/workspace"],
            ["git", "clone", "--", repository, "/workspace/project"],
        ]
        for command in commands:
            sandbox.exec(command, timeout_seconds=900, check=True).result()

        result = sandbox.exec(
            [
                "/root/.local/bin/agent",
                "--print", "--force", "--trust", "--output-format", "text",
                "Create sandbox-proof.txt containing exactly Hello from CoreWeave "
                "followed by a newline, then read it back. Do not commit or push anything.",
            ],
            cwd="/workspace/project",
            timeout_seconds=300,
            check=True,
        ).result()
        print(result.stdout)
        proof = sandbox.exec(
            ["cat", "/workspace/project/sandbox-proof.txt"], check=True
        ).result()
        print(proof.stdout, end="")
    finally:
        sandbox.stop().result()
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript title="run_cursor_sandbox.mts" theme={"system"}
    import { createSandboxClientFromEnv as coreweaveClient } from "@coreweave/cwsandbox/node";
    import { createSandboxClientFromEnv as wandbClient } from "@coreweave/cwsandbox/wandb";

    const [mode, repository] = process.argv.slice(2);
    if (!repository || (mode !== "wandb" && mode !== "coreweave")) {
      throw new Error("Pass wandb or coreweave, then a repository URL.");
    }

    const credential = mode === "wandb"
      ? process.env.CURSOR_SECRET_NAME : process.env.CURSOR_API_KEY;
    if (!credential) {
      throw new Error("Set CURSOR_SECRET_NAME for wandb or CURSOR_API_KEY for coreweave.");
    }
    const client = mode === "wandb" ? wandbClient() : coreweaveClient();
    const credentials = mode === "wandb"
      ? { secrets: [{ store: "wandb", name: credential, envVar: "CURSOR_API_KEY" }] }
      : { environmentVariables: { CURSOR_API_KEY: credential } };
    const sandbox = await client.create({
      containerImage: "node:22-bookworm",
      resources: { cpu: "2", memory: "4Gi" },
      maxLifetimeSeconds: 2 * 3600,
      ...credentials,
      waitUntilRunning: false,
    });
    try {
      await sandbox.wait();
      const commands = [
        ["bash", "-o", "pipefail", "-ec", "curl -fsSL https://cursor.com/install | bash"],
        ["mkdir", "-p", "/workspace"],
        ["git", "clone", "--", repository, "/workspace/project"],
      ];
      for (const command of commands) {
        await sandbox.commands.run(command, { timeoutMs: 900_000, check: true });
      }

      const result = await sandbox.commands.run(
        [
          "/root/.local/bin/agent",
          "--print", "--force", "--trust", "--output-format", "text",
          "Create sandbox-proof.txt containing exactly Hello from CoreWeave " +
            "followed by a newline, then read it back. Do not commit or push anything.",
        ],
        { cwd: "/workspace/project", timeoutMs: 300_000, check: true },
      );
      console.log(result.stdout);
      const proof = await sandbox.commands.run(
        ["cat", "/workspace/project/sandbox-proof.txt"], { check: true },
      );
      process.stdout.write(proof.stdout);
    } finally {
      await sandbox.stop();
    }
    ```
  </Tab>
</Tabs>

자격 증명을 설정한 로컬 터미널에서 `[AUTH-MODE]`를
`wandb`로, `[REPOSITORY-URL]`을 저장소 URL로 바꾸세요.

<Tabs>
  <Tab title="Python">
    ```bash theme={"system"}
    uv run python run_cursor_sandbox.py [AUTH-MODE] [REPOSITORY-URL]
    ```
  </Tab>

  <Tab title="TypeScript">
    ```bash theme={"system"}
    npx tsx run_cursor_sandbox.mts [AUTH-MODE] [REPOSITORY-URL]
    ```
  </Tab>
</Tabs>

The script prints Cursor's response followed by the file contents,
`Hello from CoreWeave`. The cleanup block calls `stop()` even if setup or execution
raises an error.
Retrieve any additional files before the cleanup block runs. For larger results,
use [file operations](../client/guides/file-operations).

The 2-hour lifetime is a maximum wall-clock limit, including startup. Each
command also has its own timeout. Changing the command timeout doesn't extend
the sandbox lifetime.

## Troubleshoot

Use these checks to resolve common issues:

* If sandbox creation fails, verify the credential for your selected
  authentication mode.

- W\&B 시크릿을 찾을 수 없는 경우 `WANDB_ENTITY`, `CURSOR_SECRET_NAME`,
  API 키의 팀 액세스 권한을 확인하세요.
- Cursor에서 인증 오류가 발생하면 W\&B 시크릿에 저장된 키와
  계정의 모델 액세스 권한을 확인하세요.

* If an SDK prompt only proposes changes, confirm that the Cursor command
  includes `--force`.

- 설치, 복제 또는 모델 요청이 실패하면 아웃바운드 연결과
  공급자 자격 증명을 확인하세요.

## Next steps

For more information, see these guides:

* [Run agents on CoreWeave sandboxes](.) covers placement,
  longer sessions, and workspace lifecycle.
* [Cursor with cws-agent](https://github.com/coreweave/cws-agent/blob/main/docs/cursor.md)
  covers saved conversations and configuration imports.
* [Cursor CLI documentation](https://cursor.com/docs/cli/overview) covers agent
  configuration and supported modes.
