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

# 샌드박스에서 Muse Code 실행하기

> 샌드박스의 저장소에서 Muse Code CLI를 실행하고 결과를 가져온 뒤 컴퓨팅 리소스를 중지합니다.

Run Muse Code inside a CoreWeave sandbox to edit files and execute commands in a remote workspace. This guide uses the Sandbox software development kit (SDK) to install the command-line interface (CLI) and clone a repository. You then run a task without an interactive terminal and retrieve the result before you stop the sandbox. The agent process and workspace run on CoreWeave, and model requests go to Meta.

## Prerequisites

Before you begin, you need the following:

* [W\&B API 키](https://forge.coreweave.com/settings#apikeys). 이 예시에서는 W\&B 인증을 사용합니다.
* Muse Code 액세스 권한이 있는 [Meta API 키](https://dev.meta.ai/docs/muse-code/auth).
* 샌드박스에서 클론할 수 있는 공개 저장소 URL. 비공개 저장소를 사용하려면 샌드박스 안에 Git 자격 증명이 있어야 합니다.
* `uv`가 설치된 Python 3.11 이상 또는 `npm`이 설치된 Node.js 22 이상.

시크릿 관리자에 저장된 자격 증명을 로컬 터미널 환경에 로드하세요. `[WANDB-API-KEY]`는 W\&B API 키로, `[META-API-KEY]`는 Meta API 키로 바꾸세요.

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

이 스크립트는 Meta 키를 표준 입력으로 전달하므로 키가 명령 인수나 샌드박스 설정에 노출되지 않습니다. 샌드박스 생성 시 환경 변수로 주입되는 팀 공유 자격 증명에 대해서는 [W\&B 시크릿](/ko/products/sandboxes/serverless/secrets)을 참조하세요.

## Install the Sandbox client

Choose a language and prepare a local project:

<Tabs>
  <Tab title="Python">
    ```bash theme={"system"}
    mkdir muse-sandbox
    cd muse-sandbox
    uv init --bare --python 3.11
    uv venv --python 3.11
    source .venv/bin/activate
    uv pip install 'cwsandbox[wandb]>=1.14.2'
    ```
  </Tab>

  <Tab title="TypeScript">
    ```bash theme={"system"}
    mkdir muse-sandbox
    cd muse-sandbox
    npm init -y
    npm install @coreweave/cwsandbox@0.5.0-beta.0 tsx
    ```
  </Tab>
</Tabs>

## Run a task in the sandbox

Save the script for your language using the filename shown. Each script creates a serverless sandbox with a 30-minute maximum lifetime and performs these steps:

1. Installs Muse Code with Meta's installer.
2. Clones your repository into the `/workspace/project` directory.
3. Runs `muse exec` to build and test a sparkline CLI that renders numbers as a small chart.
4. Runs the generated CLI independently, checks its output, and saves the `sparkline.mjs` file locally.
5. Stops the sandbox in a `finally` block, including when setup or execution fails.

These examples were tested with Muse Code 1.3.0. The installer can install a newer version, so each script runs `muse --version` after installation.

The example uses `--yolo` to disable Muse Code's approval prompts and operating system (OS) sandbox and trust the workspace for this run. CoreWeave supplies the outer sandbox. Muse can access files, credentials, and network destinations available inside that sandbox. Use a repository you trust and provide only the credentials the task needs. For more information, see [Muse Code permissions](https://dev.meta.ai/docs/muse-code/permissions).

<Tabs>
  <Tab title="Python">
    ```python title="run_muse.py" theme={"system"}
    import os
    import sys
    from pathlib import Path

    from cwsandbox import AuthStrategy, Sandbox

    if len(sys.argv) != 2:
        raise SystemExit("Usage: python run_muse.py [REPOSITORY-URL]")
    meta_api_key = os.environ["META_API_KEY"]

    sandbox = Sandbox.run(
        auth=AuthStrategy.WANDB,
        container_image="node:22-bookworm",
        resources={"cpu": "2", "memory": "4Gi"},
        max_lifetime_seconds=1800,
        tags=["muse-code"],
    )
    try:
        sandbox.wait()
        commands = [
            ["bash", "-o", "pipefail", "-ec", "curl -fsSL https://dev.meta.ai/install.sh | bash"],
            ["bash", "-ec", '"$HOME/.local/bin/muse" --version'],
            ["git", "clone", "--", sys.argv[1], "/workspace/project"],
        ]
        for command in commands:
            result = sandbox.exec(command, timeout_seconds=600, check=True).result()
            print(result.stdout, end="")

        agent = sandbox.exec(
            [
                "bash", "-ec",
                'IFS= read -r META_API_KEY; export META_API_KEY; '
                'exec "$HOME/.local/bin/muse" exec --yolo "$1"',
                "bash",
                "Create sparkline.mjs, a dependency-free Node.js CLI that converts its "
                "numeric arguments to a sparkline using ▁▂▃▄▅▆▇█. Scale from the minimum "
                "to the maximum and round to the nearest bar index. "
                "Running node sparkline.mjs 2 4 8 4 2 must print ▁▃█▃▁ followed by "
                "a newline. Run that command to test it.",
            ],
            cwd="/workspace/project",
            stdin=True,
            timeout_seconds=600,
        )
        # 한동안 출력이 없는 요청이 중단되지 않도록 Muse가 종료될 때까지 stdin을 열어 둡니다.
        agent.stdin.writeline(meta_api_key).result()
        result = agent.result()
        print(result.stdout, end="")
        print(result.stderr, end="", file=sys.stderr)
        if result.returncode != 0:
            raise SystemExit(result.returncode)

        chart = sandbox.exec(
            ["node", "sparkline.mjs", "2", "4", "8", "4", "2"],
            cwd="/workspace/project", check=True,
        ).result()
        if chart.stdout != "▁▃█▃▁\n":
            raise RuntimeError(f"Unexpected sparkline: {chart.stdout!r}")
        print(chart.stdout, end="")
        source = sandbox.exec(
            ["cat", "/workspace/project/sparkline.mjs"], check=True
        ).result()
        Path("sparkline.mjs").write_text(source.stdout, encoding="utf-8")
    finally:
        sandbox.stop().result()
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript title="run_muse.mts" theme={"system"}
    import { writeFile } from "node:fs/promises";
    import { createSandboxClientFromEnv } from "@coreweave/cwsandbox/wandb";

    const repository = process.argv[2];
    if (!repository) throw new Error("Pass a repository URL.");
    const metaApiKey = process.env.META_API_KEY;
    if (!metaApiKey) throw new Error("Set META_API_KEY.");

    const client = createSandboxClientFromEnv();
    const sandbox = await client.create({
      containerImage: "node:22-bookworm",
      resources: { cpu: "2", memory: "4Gi" },
      maxLifetimeSeconds: 1800,
      waitUntilRunning: false,
      tags: ["muse-code"],
    });
    try {
      await sandbox.wait();
      const commands = [
        ["bash", "-o", "pipefail", "-ec", "curl -fsSL https://dev.meta.ai/install.sh | bash"],
        ["bash", "-ec", '"$HOME/.local/bin/muse" --version'],
        ["git", "clone", "--", repository, "/workspace/project"],
      ];
      for (const command of commands) {
        const result = await sandbox.commands.run(command, { timeoutMs: 600_000, check: true });
        process.stdout.write(result.stdout);
      }

      const agent = await sandbox.commands.start(
        [
          "bash", "-ec",
          'IFS= read -r META_API_KEY; export META_API_KEY; ' +
            'exec "$HOME/.local/bin/muse" exec --yolo "$1"',
          "bash",
          "Create sparkline.mjs, a dependency-free Node.js CLI that converts its " +
            "numeric arguments to a sparkline using ▁▂▃▄▅▆▇█. Scale from the minimum " +
            "to the maximum and round to the nearest bar index. " +
            "Running node sparkline.mjs 2 4 8 4 2 must print ▁▃█▃▁ followed by " +
            "a newline. Run that command to test it.",
        ],
        {
          cwd: "/workspace/project",
          stdin: true,
          timeoutMs: 600_000,
        },
      );
      // 출력이 없는 요청이 중단되지 않도록 Muse가 끝날 때까지 stdin을 열어 둡니다.
      await agent.stdin.write(metaApiKey + "\n");
      const result = await agent.wait();
      process.stdout.write(result.stdout);
      process.stderr.write(result.stderr);
      if (!result.ok) throw new Error(`Muse Code exited with code ${result.exitCode}.`);

      const chart = await sandbox.commands.run(
        ["node", "sparkline.mjs", "2", "4", "8", "4", "2"],
        { cwd: "/workspace/project", check: true },
      );
      if (chart.stdout !== "▁▃█▃▁\n") {
        throw new Error(`Unexpected sparkline: ${JSON.stringify(chart.stdout)}`);
      }
      process.stdout.write(chart.stdout);
      const source = await sandbox.commands.run(
        ["cat", "/workspace/project/sparkline.mjs"], { check: true },
      );
      await writeFile("sparkline.mjs", source.stdout, "utf8");
    } finally {
      await sandbox.stop();
    }
    ```
  </Tab>
</Tabs>

In your local project directory, replace `[REPOSITORY-URL]` with your public repository URL, then run the script:

<Tabs>
  <Tab title="Python">
    ```bash theme={"system"}
    python run_muse.py [REPOSITORY-URL]
    ```
  </Tab>

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

After the installation and agent output, the script checks and prints the sparkline:

```text theme={"system"}
▁▃█▃▁
```

The script saves the generated `sparkline.mjs` file in your local project directory, then stops the sandbox. If the file already exists locally, the script overwrites it. The output check runs independently of Muse's own test and verifies this example's input. For a larger task, replace it with tests for your requirements.

이 예시에서는 영구 저장소를 설정하지 않습니다. `finally` 블록이 실행되기 전에 필요한 파일을 샌드박스 밖으로 복사하세요. 자세한 내용은 [파일 오퍼레이션](/ko/products/sandboxes/serverless/client/guides/file-operations) 및 [파일 시스템 스냅샷](/products/sandboxes/serverless/file-system-snapshots)을 참조하세요.

## Troubleshoot

Use these checks to resolve common issues:

* 샌드박스 생성에 실패하면 W\&B 키와 인증 설정을 확인하세요.
* Muse Code에서 인증 오류가 발생하면 `META_API_KEY`와 Meta 계정 설정을 확인하세요. 샌드박스 자격 증명은 모델 요청 인증에 사용되지 않습니다.
* 설치, 클론 또는 모델 요청에 실패하면 Meta와 Git 호스트로의 아웃바운드 액세스를 확인하세요.
* 규모가 큰 작업에서 시간 초과가 발생하면 실행 전에 명령 timeout과 샌드박스 수명을 조정하세요. 30분의 수명에는 시작 및 설치 시간이 포함됩니다. 자세한 내용은 [명령 timeout](/ko/products/sandboxes/serverless/client/guides/execution#set-a-timeout) 및 [샌드박스 라이프사이클](/ko/products/sandboxes/serverless/client/guides/sandbox-lifecycle)을 참조하세요.

## Next steps

For more information, see these guides:

* [Interactive shells and TTY](../client/guides/interactive-shells) covers terminal access for interactive agents.
* [Run agents on CoreWeave sandboxes](.) compares agent integrations and workspace options.
* [Meta's sandboxed execution cookbook](https://dev.meta.ai/docs/cookbook/sandboxed-execution) demonstrates a reproduce, fix, and verify workflow with a custom tool loop in Docker.
* [Muse Code documentation](https://dev.meta.ai/docs/muse-code) covers agent configuration and other CLI workflows.
