## 1. Project Overview & Quickstart (daytonaio/LICENSE)

# LICENSE

Open-source repository daytonaio/LICENSE

### Repository Details
- **Repository:** [daytonaio/LICENSE](https://github.com/daytonaio/LICENSE)
- **Primary Language:** Code

*Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.*

## 2. Official Technical Reference & Guides (daytonaio/docs)

## File: README.md

# Contents of this repository were transferred to the [Daytona](https://github.com/daytonaio/daytona) repo.








<h1 align="center">Daytona Documentation</h1>





The Daytona Documentation is developed with Astro and Starlight.
Its core architecture leverages React, while documentation content is authored using Markdown (MDX).

## Getting Started

If Node.js or Yarn are installed and set up on your local machine, you can clone this repository and install the required dependencies and configurations:

```shell
git clone https://github.com/daytonaio/docs.git
```

```shell
yarn install
```

### Useful Commands

This repository utilizes `Yarn` to manage project dependencies and custom scripts. Below is a list of commonly used commands, defined in the `package.json`:

| Command                    | Action                                                                                                    |
| :------------------------- | :-------------------------------------------------------------------------------------------------------- |
| `yarn dev`                 | Starts the local development server at `localhost:4321`.                                                  |
| `yarn build`               | Builds the production site to the `./dist/` directory.                                                    |
| `yarn preview`             | Previews the production build locally before deployment.                                                  |
| `yarn astro [command]`     | Runs Astro CLI commands.                                                                                  |
| `yarn astro -- --help`     | Displays help information for the Astro CLI.                                                              |
| `yarn update-cli-reference`| Updates the Daytona CLI reference using autogenerated CLI documentation.                                  |
| `yarn update-search`       | Updates the Daytona documentation search index.                                                           |
| `yarn update-llms`         | Updates the Daytona documentation links index following the [`/llms.txt`](https://llmstxt.org/) standard. |

### Documentation Structure

The documentation is organized as `.mdx` files within the `/src/content/docs` directory.
Daytona documentation is divided into the following key sections:

- **`Home`**

  Overview of Daytona's SDK interfaces and quick start instructions.

- **`Getting Started`**

  Instructions for installing Daytona across various environments.

- **`Configuration`**

  Guides to configuring Daytona's core options.

- **`Management`**

  Practical instructions for managing Daytona sandboxes.

- **`Agent Toolbox`**

  Information about the File System actions, Git Operations, the Language Server Protocol and Process & Code Execution.

## Contributing

Daytona is licensed under the [Apache License 2.0](LICENSE). If you would like to contribute to the software, you must:

1. Read the Developer Certificate of Origin Version 1.1 (<https://developercertificate.org/>)
2. Sign all commits to the Daytona project.

This ensures that users, distributors, and other contributors can rely on all the software related to Daytona being contributed under the terms of the [License](LICENSE). No contributions will be accepted without following this process.

## License

This repository contains Daytona's Documentation website, covered under the Apache License 2.0, except where noted (any Daytona logos or trademarks are not covered under the Apache License, and should be explicitly noted by a LICENSE file.)

Daytona is a product produced from this open source software, exclusively by Daytona Platforms, Inc. It is distributed under our commercial terms.

Others are allowed to make their own distribution of the software, but they cannot use any of the Daytona trademarks, cloud services, etc.

We explicitly grant permission for you to make a build that includes our trademarks while developing Daytona itself. You may not publish or share the build, and you may not use that build to run Daytona for any other purpose.

## Code of Conduct

This project has adapted the Code of Conduct from the [Contributor Covenant](https://www.contributor-covenant.org/). For more information see the [Code of Conduct](CODE_OF_CONDUCT.md) or contact [codeofconduct@daytona.io.](mailto:codeofconduct@daytona.io) with any additional questions or comments.

## Questions

If you need guidance on contributing to Daytona, talk to us on
[Slack](https://go.daytona.io/slack).

---

## File: src/content/docs/python-sdk/common/charts.mdx

---
title: "Charts"
hideTitleOnPage: true
---

## Chart

```python
class Chart()
```

Represents a chart with metadata from matplotlib.

**Attributes**:

- `type` _ChartType_ - The type of chart
- `title` _str_ - The title of the chart
- `elements` _List[Any]_ - The elements of the chart
- `png` _Optional[str]_ - The PNG representation of the chart encoded in base64

## ChartType

```python
class ChartType(str, Enum)
```

Chart types

**Enum Members**:
    - `LINE` ("line")
    - `SCATTER` ("scatter")
    - `BAR` ("bar")
    - `PIE` ("pie")
    - `BOX_AND_WHISKER` ("box_and_whisker")
    - `COMPOSITE_CHART` ("composite_chart")
    - `UNKNOWN` ("unknown")

## Chart2D

```python
class Chart2D(Chart)
```

Represents a 2D chart with metadata.

**Attributes**:

- `x_label` _Optional[str]_ - The label of the x-axis
- `y_label` _Optional[str]_ - The label of the y-axis

## PointData

```python
class PointData()
```

Represents a point in a 2D chart.

**Attributes**:

- `label` _str_ - The label of the point
- `points` _List[Tuple[Union[str, float], Union[str, float]]]_ - The points of the chart

## PointChart

```python
class PointChart(Chart2D)
```

Represents a point chart with metadata.

**Attributes**:

- `x_ticks` _List[Union[str, float]]_ - The ticks of the x-axis
- `x_tick_labels` _List[str]_ - The labels of the x-axis
- `x_scale` _str_ - The scale of the x-axis
- `y_ticks` _List[Union[str, float]]_ - The ticks of the y-axis
- `y_tick_labels` _List[str]_ - The labels of the y-axis
- `y_scale` _str_ - The scale of the y-axis
- `elements` _List[PointData]_ - The points of the chart

## LineChart

```python
class LineChart(PointChart)
```

Represents a line chart with metadata.

**Attributes**:

- `type` _ChartType_ - The type of chart

## ScatterChart

```python
class ScatterChart(PointChart)
```

Represents a scatter chart with metadata.

**Attributes**:

- `type` _ChartType_ - The type of chart

## BarData

```python
class BarData()
```

Represents a bar in a bar chart.

**Attributes**:

- `label` _str_ - The label of the bar
- `group` _str_ - The group of the bar
- `value` _str_ - The value of the bar

## BarChart

```python
class BarChart(Chart2D)
```

Represents a bar chart with metadata.

**Attributes**:

- `type` _ChartType_ - The type of chart
- `elements` _List[BarData]_ - The bars of the chart

## PieData

```python
class PieData()
```

Represents a pie slice in a pie chart.

**Attributes**:

- `label` _str_ - The label of the pie slice
- `angle` _float_ - The angle of the pie slice
- `radius` _float_ - The radius of the pie slice
- `autopct` _float_ - The autopct value of the pie slice

## PieChart

```python
class PieChart(Chart)
```

Represents a pie chart with metadata.

**Attributes**:

- `type` _ChartType_ - The type of chart
- `elements` _List[PieData]_ - The pie slices of the chart

## BoxAndWhiskerData

```python
class BoxAndWhiskerData()
```

Represents a box and whisker in a box and whisker chart.

**Attributes**:

- `label` _str_ - The label of the box and whisker
- `min` _float_ - The minimum value of the box and whisker
- `first_quartile` _float_ - The first quartile of the box and whisker
- `median` _float_ - The median of the box and whisker
- `third_quartile` _float_ - The third quartile of the box and whisker
- `max` _float_ - The maximum value of the box and whisker
- `outliers` _List[float]_ - The outliers of the box and whisker

## BoxAndWhiskerChart

```python
class BoxAndWhiskerChart(Chart2D)
```

Represents a box and whisker chart with metadata.

**Attributes**:

- `type` _ChartType_ - The type of chart
- `elements` _List[BoxAndWhiskerData]_ - The box and whiskers of the chart

## CompositeChart

```python
class CompositeChart(Chart)
```

Represents a composite chart with metadata. A composite chart is a chart
that contains multiple charts (subplots).

**Attributes**:

- `type` _ChartType_ - The type of chart
- `elements` _List[Chart]_ - The charts (subplots) of the composite chart

---

## File: src/content/docs/python-sdk/common/errors.mdx

---
title: "Errors"
hideTitleOnPage: true
---

## DaytonaError

```python
class DaytonaError(Exception)
```

Base error for Daytona SDK.

---

## File: src/content/docs/python-sdk/common/image.mdx

---
title: "Image"
hideTitleOnPage: true
---

## Image

```python
class Image(BaseModel)
```

Represents an image definition for a Daytona sandbox.
Do not construct this class directly. Instead use one of its static factory methods,
such as `Image.base()`, `Image.debian_slim()`, or `Image.from_dockerfile()`.

#### Image.dockerfile

```python
def dockerfile() -> str
```

Returns a generated Dockerfile for the image.

#### Image.pip\_install

```python
def pip_install(*packages: Union[str, list[str]],
                find_links: Optional[list[str]] = None,
                index_url: Optional[str] = None,
                extra_index_urls: Optional[list[str]] = None,
                pre: bool = False,
                extra_options: str = "") -> "Image"
```

Adds commands to install packages using pip.

**Arguments**:

- `*packages` - The packages to install.
- `find_links` - Optional[list[str]]: The find-links to use.
- `index_url` - Optional[str]: The index URL to use.
- `extra_index_urls` - Optional[list[str]]: The extra index URLs to use.
- `pre` - bool = False: Whether to install pre-release packages.
- `extra_options` - str = "": Additional options to pass to pip. Given string is passed
  directly to the pip install command.
  
**Returns**:

- `Image` - The image with the pip install commands added.
  
**Example**:

```python
image = Image.debian_slim("3.12").pip_install("requests", "pandas")
```

#### Image.pip\_install\_from\_requirements

```python
def pip_install_from_requirements(requirements_txt: str,
                                  find_links: Optional[list[str]] = None,
                                  index_url: Optional[str] = None,
                                  extra_index_urls: Optional[list[str]] = None,
                                  pre: bool = False,
                                  extra_options: str = "") -> "Image"
```

Installs dependencies from a requirements.txt file.

**Arguments**:

- `requirements_txt` - str: The path to the requirements.txt file.
- `find_links` - Optional[list[str]]: The find-links to use.
- `index_url` - Optional[str]: The index URL to use.
- `extra_index_urls` - Optional[list[str]]: The extra index URLs to use.
- `pre` - bool = False: Whether to install pre-release packages.
- `extra_options` - str = "": Additional options to pass to pip.
  
**Returns**:

- `Image` - The image with the pip install commands added.
  
**Example**:

```python
image = Image.debian_slim("3.12").pip_install_from_requirements("requirements.txt")
```

#### Image.pip\_install\_from\_pyproject

```python
def pip_install_from_pyproject(pyproject_toml: str,
                               optional_dependencies: list[str],
                               find_links: Optional[str] = None,
                               index_url: Optional[str] = None,
                               extra_index_url: Optional[str] = None,
                               pre: bool = False,
                               extra_options: str = "") -> "Image"
```

Installs dependencies from a pyproject.toml file.

**Arguments**:

- `pyproject_toml` - str: The path to the pyproject.toml file.
- `optional_dependencies` - list[str] = []: The optional dependencies to install from the pyproject.toml file.
- `find_links` - Optional[str] = None: The find-links to use.
- `index_url` - Optional[str] = None: The index URL to use.
- `extra_index_url` - Optional[str] = None: The extra index URL to use.
- `pre` - bool = False: Whether to install pre-release packages.
- `extra_options` - str = "": Additional options to pass to pip. Given string is passed
  directly to the pip install command.
  
**Returns**:

- `Image` - The image with the pip install commands added.
  
**Example**:

```python
image = Image.debian_slim("3.12")                 .pip_install_from_pyproject("pyproject.toml", optional_dependencies=["dev"])
```

#### Image.add\_local\_file

```python
def add_local_file(local_path: Union[str, Path], remote_path: str) -> "Image"
```

Adds a local file to the image.

**Arguments**:

- `local_path` - Union[str, Path]: The path to the local file.
- `remote_path` - str: The path to the file in the image.
  
**Returns**:

- `Image` - The image with the local file added.
  
**Example**:

```python
image = Image.debian_slim("3.12").add_local_file("package.json", "/home/daytona/package.json")
```

#### Image.add\_local\_dir

```python
def add_local_dir(local_path: Union[str, Path], remote_path: str) -> "Image"
```

Adds a local directory to the image.

**Arguments**:

- `local_path` - Union[str, Path]: The path to the local directory.
- `remote_path` - str: The path to the directory in the image.
  
**Returns**:

- `Image` - The image with the local directory added.
  
**Example**:

```python
image = Image.debian_slim("3.12").add_local_dir("src", "/home/daytona/src")
```

#### Image.run\_commands

```python
def run_commands(*commands: Union[str, list[str]]) -> "Image"
```

Runs commands in the image.

**Arguments**:

- `*commands` - The commands to run.
  
**Returns**:

- `Image` - The image with the commands added.
  
**Example**:

```python
image = Image.debian_slim("3.12").run_commands(
    'echo "Hello, world!"',
    ['bash', '-c', 'echo Hello, world, again!']
)
```

#### Image.env

```python
def env(env_vars: dict[str, str]) -> "Image"
```

Sets environment variables in the image.

**Arguments**:

- `env_vars` - dict[str, str]: The environment variables to set.
  
**Returns**:

- `Image` - The image with the environment variables added.
  
**Example**:

```python
image = Image.debian_slim("3.12").env({"PROJECT_ROOT": "/home/daytona"})
```

#### Image.workdir

```python
def workdir(path: Union[str, Path]) -> "Image"
```

Sets the working directory in the image.

**Arguments**:

- `path` - Union[str, Path]: The path to the working directory.
  
**Returns**:

- `Image` - The image with the working directory added.
  
**Example**:

```python
image = Image.debian_slim("3.12").workdir("/home/daytona")
```

#### Image.entrypoint

```python
def entrypoint(entrypoint_commands: list[str]) -> "Image"
```

Sets the entrypoint for the image.

**Arguments**:

- `entrypoint_commands` - list[str]: The commands to set as the entrypoint.
  
**Returns**:

- `Image` - The image with the entrypoint added.
  
**Example**:

```python
image = Image.debian_slim("3.12").entrypoint(["/bin/bash"])
```

#### Image.cmd

```python
def cmd(cmd: list[str]) -> "Image"
```

Sets the default command for the image.

**Arguments**:

- `cmd` - list[str]: The commands to set as the default command.
  
**Returns**:

- `Image` - The image with the default command added.
  
**Example**:

```python
image = Image.debian_slim("3.12").cmd(["/bin/bash"])
```

#### Image.dockerfile\_commands

```python
def dockerfile_commands(
        dockerfile_commands: list[str],
        context_dir: Optional[Union[Path, str]] = None) -> "Image"
```

Adds arbitrary Dockerfile-like commands to the image.

**Arguments**:

- `*dockerfile_commands` - The commands to add to the Dockerfile.
- `context_dir` - Optional[Union[Path, str]]: The path to the context directory.
  
**Returns**:

- `Image` - The image with the Dockerfile commands added.
  
**Example**:

```python
image = Image.debian_slim("3.12").dockerfile_commands(["RUN echo 'Hello, world!'"])
```

#### Image.from\_dockerfile

```python
@staticmethod
def from_dockerfile(path: Union[str, Path]) -> "Image"
```

Creates an Image from an existing Dockerfile.

**Arguments**:

- `path` - Union[str, Path]: The path to the Dockerfile.
  
**Returns**:

- `Image` - The image with the Dockerfile added.
  
**Example**:

```python
image = Image.from_dockerfile("Dockerfile")
```

#### Image.base

```python
@staticmethod
def base(image: str) -> "Image"
```

Creates an Image from an existing base image.

**Arguments**:

- `image` - str: The base image to use.
  
**Returns**:

- `Image` - The image with the base image added.
  
**Example**:

```python
image = Image.base("python:3.12-slim-bookworm")
```

#### Image.debian\_slim

```python
@staticmethod
def debian_slim(
        python_version: Optional[SupportedPythonSeries] = None) -> "Image"
```

Creates a Debian slim image based on the official Python Docker image.

**Arguments**:

- `python_version` - Optional[SupportedPythonSeries]: The Python version to use.
  
**Returns**:

- `Image` - The image with the Debian slim image added.
  
**Example**:

```python
image = Image.debian_slim("3.12")
```

## Context

```python
class Context(BaseModel)
```

Context for an image.

**Attributes**:

- `source_path` _str_ - The path to the source file or directory.
- `archive_path` _Optional[str]_ - The path inside the archive file in object storage.

---

## File: src/content/docs/python-sdk/async/async-daytona.mdx

---
title: "AsyncDaytona"
hideTitleOnPage: true
---

## AsyncDaytona

```python
class AsyncDaytona()
```

Main class for interacting with the Daytona API.

This class provides asynchronous methods to create, manage, and interact with Daytona Sandboxes.
It can be initialized either with explicit configuration or using environment variables.

**Attributes**:

- `volume` _AsyncVolumeService_ - Service for managing volumes.
- `snapshot` _AsyncSnapshotService_ - Service for managing snapshots.
  
**Example**:

  Using environment variables:

```python
async with AsyncDaytona() as daytona:  # Uses DAYTONA_API_KEY, DAYTONA_API_URL
    sandbox = await daytona.create()
```
  
  Using explicit configuration:

```python
config = DaytonaConfig(
    api_key="your-api-key",
    api_url="https://your-api.com",
    target="us"
)
try:
    daytona = AsyncDaytona(config)
    sandbox = await daytona.create()
finally:
    await daytona.close()
```

#### AsyncDaytona.\_\_init\_\_

```python
def __init__(config: Optional[DaytonaConfig] = None)
```

Initializes Daytona instance with optional configuration.

If no config is provided, reads from environment variables:

- `DAYTONA_API_KEY`: Required API key for authentication
- `DAYTONA_API_URL`: Required api URL
- `DAYTONA_TARGET`: Optional target environment (defaults to 'us')

**Arguments**:

- `config` _Optional[DaytonaConfig]_ - Object containing api_key, api_url, and target.
  
**Raises**:

- `DaytonaError` - If API key is not provided either through config or environment variables
  
**Example**:

```python
from daytona import Daytona, DaytonaConfig
# Using environment variables
daytona1 = AsyncDaytona()
await daytona1.close()
# Using explicit configuration
config = DaytonaConfig(
    api_key="your-api-key",
    api_url="https://your-api.com",
    target="us"
)
daytona2 = AsyncDaytona(config)
await daytona2.close()
```

#### AsyncDaytona.\_\_aenter\_\_

```python
async def __aenter__()
```

Async context manager entry.

#### AsyncDaytona.\_\_aexit\_\_

```python
async def __aexit__(exc_type, exc_value, traceback)
```

Async context manager exit - ensures proper cleanup.

#### AsyncDaytona.close

```python
async def close()
```

Close the HTTP session and clean up resources.

This method should be called when you're done using the AsyncDaytona instance
to properly close the underlying HTTP session and avoid resource leaks.

**Example**:

```python
daytona = AsyncDaytona()
try:
    sandbox = await daytona.create()
    # ... use sandbox ...
finally:
    await daytona.close()
```
  
  Or better yet, use as async context manager:

```python
async with AsyncDaytona() as daytona:
    sandbox = await daytona.create()
    # ... use sandbox ...
# Automatically closed
```

#### AsyncDaytona.create

```python
@overload
async def create(params: Optional[CreateSandboxFromSnapshotParams] = None,
                 *,
                 timeout: Optional[float] = 60) -> AsyncSandbox
```

Creates Sandboxes from specified or default snapshot. You can specify various parameters,
including language, image, environment variables, and volumes.

**Arguments**:

- `params` _Optional[CreateSandboxFromSnapshotParams]_ - Parameters for Sandbox creation. If not provided,
  defaults to default Daytona snapshot and Python language.
- `timeout` _Optional[float]_ - Timeout (in seconds) for sandbox creation. 0 means no timeout.
  Default is 60 seconds.
  
**Returns**:

- `Sandbox` - The created Sandbox instance.
  
**Raises**:

- `DaytonaError` - If timeout, auto_stop_interval or auto_archive_interval is negative;
  If sandbox fails to start or times out
  
**Example**:

  Create a default Python Sandbox:

```python
sandbox = await daytona.create()
```
  
  Create a custom Sandbox:

```python
params = CreateSandboxFromSnapshotParams(
    language="python",
    snapshot="my-snapshot-id",
    env_vars={"DEBUG": "true"},
    auto_stop_interval=0,
    auto_archive_interval=60
)
sandbox = await daytona.create(params, timeout=40)
```

#### AsyncDaytona.create

```python
@overload
async def create(
        params: Optional[CreateSandboxFromImageParams] = None,
        *,
        timeout: Optional[float] = 60,
        on_snapshot_create_logs: Callable[[str], None] = None) -> AsyncSandbox
```

Creates Sandboxes from specified image available on some registry or declarative Daytona Image.
You can specify various parameters, including resources, language, image, environment variables,
and volumes. Daytona creates snapshot from provided image and uses it to create Sandbox.

**Arguments**:

- `params` _Optional[CreateSandboxFromImageParams]_ - Parameters for Sandbox creation from image.
- `timeout` _Optional[float]_ - Timeout (in seconds) for sandbox creation. 0 means no timeout.
  Default is 60 seconds.
- `on_snapshot_create_logs` _Callable[[str], None]_ - This callback function handles snapshot creation logs.
  
**Returns**:

- `Sandbox` - The created Sandbox instance.
  
**Raises**:

- `DaytonaError` - If timeout, auto_stop_interval or auto_archive_interval is negative;
  If sandbox fails to start or times out
  
**Example**:

  Create a default Python Sandbox from image:

```python
sandbox = await daytona.create(CreateSandboxFromImageParams(image="debian:12.9"))
```
  
  Create a custom Sandbox from declarative Image definition:

```python
declarative_image = (
    Image.base("alpine:3.18")
    .pipInstall(["numpy", "pandas"])
    .env({"MY_ENV_VAR": "My Environment Variable"})
)
params = CreateSandboxFromImageParams(
    language="python",
    image=declarative_image,
    env_vars={"DEBUG": "true"},
    resources=Resources(cpu=2, memory=4),
    auto_stop_interval=0,
    auto_archive_interval=60,
)
sandbox = await daytona.create(
    params,
    timeout=40,
    on_snapshot_create_logs=lambda chunk: print(chunk, end=""),
)
```

#### AsyncDaytona.delete

```python
@intercept_errors(message_prefix="Failed to remove sandbox: ")
async def delete(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> None
```

Deletes a Sandbox.

**Arguments**:

- `sandbox` _Sandbox_ - The Sandbox instance to delete.
- `timeout` _Optional[float]_ - Timeout (in seconds) for sandbox deletion. 0 means no timeout.
  Default is 60 seconds.
  
**Raises**:

- `DaytonaError` - If sandbox fails to delete or times out
  
**Example**:

```python
sandbox = await daytona.create()
# ... use sandbox ...
await daytona.delete(sandbox)  # Clean up when done
```

#### AsyncDaytona.get

```python
@intercept_errors(message_prefix="Failed to get sandbox: ")
async def get(sandbox_id: str) -> AsyncSandbox
```

Gets a Sandbox by its ID.

**Arguments**:

- `sandbox_id` _str_ - The ID of the Sandbox to retrieve.
  
**Returns**:

- `Sandbox` - The Sandbox instance.
  
**Raises**:

- `DaytonaError` - If sandbox_id is not provided.
  
**Example**:

```python
sandbox = await daytona.get("my-sandbox-id")
print(sandbox.status)
```

#### AsyncDaytona.find\_one

```python
@intercept_errors(message_prefix="Failed to find sandbox: ")
async def find_one(sandbox_id: Optional[str] = None,
                   labels: Optional[Dict[str, str]] = None) -> AsyncSandbox
```

Finds a Sandbox by its ID or labels.

**Arguments**:

- `sandbox_id` _Optional[str]_ - The ID of the Sandbox to retrieve.
- `labels` _Optional[Dict[str, str]]_ - Labels to filter Sandboxes.
  
**Returns**:

- `Sandbox` - First Sandbox that matches the ID or labels.
  
**Raises**:

- `DaytonaError` - If no Sandbox is found.
  
**Example**:

```python
sandbox = await daytona.find_one(labels={"my-label": "my-value"})
print(f"Sandbox ID: {sandbox.id} State: {sandbox.state}")
```

#### AsyncDaytona.list

```python
@intercept_errors(message_prefix="Failed to list sandboxes: ")
async def list(labels: Optional[Dict[str, str]] = None) -> List[AsyncSandbox]
```

Lists Sandboxes filtered by labels.

**Arguments**:

- `labels` _Optional[Dict[str, str]]_ - Labels to filter Sandboxes.
  
**Returns**:

- `List[Sandbox]` - List of Sandbox instances that match the labels.
  
**Example**:

```python
sandboxes = await daytona.list(labels={"my-label": "my-value"})
for sandbox in sandboxes:
    print(f"{sandbox.id}: {sandbox.status}")
```

#### AsyncDaytona.start

```python
async def start(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> None
```

Starts a Sandbox and waits for it to be ready.

**Arguments**:

- `sandbox` _Sandbox_ - The Sandbox to start.
- `timeout` _Optional[float]_ - Optional timeout in seconds to wait for the Sandbox to start.
  0 means no timeout. Default is 60 seconds.
  
**Raises**:

- `DaytonaError` - If timeout is negative; If Sandbox fails to start or times out

#### AsyncDaytona.stop

```python
async def stop(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> None
```

Stops a Sandbox and waits for it to be stopped.

**Arguments**:

- `sandbox` _Sandbox_ - The sandbox to stop
- `timeout` _Optional[float]_ - Optional timeout (in seconds) for sandbox stop.
  0 means no timeout. Default is 60 seconds.
  
**Raises**:

- `DaytonaError` - If timeout is negative; If Sandbox fails to stop or times out

## CodeLanguage

```python
@dataclass
class CodeLanguage(Enum)
```

Programming languages supported by Daytona

**Enum Members**:
    - `PYTHON` ("python")
    - `TYPESCRIPT` ("typescript")
    - `JAVASCRIPT` ("javascript")

## DaytonaConfig

```python
class DaytonaConfig(BaseModel)
```

Configuration options for initializing the Daytona client.

**Attributes**:

- `api_key` _Optional[str]_ - API key for authentication with the Daytona API. If not set, it must be provided
  via the environment variable `DAYTONA_API_KEY`, or a JWT token must be provided instead.
- `jwt_token` _Optional[str]_ - JWT token for authentication with the Daytona API. If not set, it must be provided
  via the environment variable `DAYTONA_JWT_TOKEN`, or an API key must be provided instead.
- `organization_id` _Optional[str]_ - Organization ID used for JWT-based authentication. Required if a JWT token
  is provided, and must be set either here or in the environment variable `DAYTONA_ORGANIZATION_ID`.
- `api_url` _Optional[str]_ - URL of the Daytona API. Defaults to `'https://app.daytona.io/api'` if not set
  here or in the environment variable `DAYTONA_API_URL`.
- `server_url` _Optional[str]_ - Deprecated. Use `api_url` instead. This property will be removed
  in a future version.
- `target` _Optional[SandboxTargetRegion]_ - Target environment for the Sandbox. Defaults to `'us'` if not set here
  or in the environment variable `DAYTONA_TARGET`.
  
**Example**:

```python
config = DaytonaConfig(api_key="your-api-key")
```

```python
config = DaytonaConfig(jwt_token="your-jwt-token", organization_id="your-organization-id")
```

## CreateSandboxBaseParams

```python
class CreateSandboxBaseParams(BaseModel)
```

Base parameters for creating a new Sandbox.

**Attributes**:

- `language` _Optional[CodeLanguage]_ - Programming language for the Sandbox. Defaults to "python".
- `os_user` _Optional[str]_ - OS user for the Sandbox.
- `env_vars` _Optional[Dict[str, str]]_ - Environment variables to set in the Sandbox.
- `labels` _Optional[Dict[str, str]]_ - Custom labels for the Sandbox.
- `public` _Optional[bool]_ - Whether the Sandbox should be public.
- `timeout` _Optional[float]_ - Timeout in seconds for Sandbox to be created and started.
- `auto_stop_interval` _Optional[int]_ - Interval in minutes after which Sandbox will
  automatically stop if no Sandbox event occurs during that time. Default is 15 minutes.
  0 means no auto-stop.
- `auto_archive_interval` _Optional[int]_ - Interval in minutes after which a continuously stopped Sandbox will
  automatically archive. Default is 7 days.
  0 means the maximum interval will be used.

## CreateSandboxFromImageParams

```python
class CreateSandboxFromImageParams(CreateSandboxBaseParams)
```

Parameters for creating a new Sandbox from an image.

**Attributes**:

- `image` _Union[str, Image]_ - Custom Docker image to use for the Sandbox. If an Image object is provided,
  the image will be dynamically built.
- `resources` _Optional[Resources]_ - Resource configuration for the Sandbox. If not provided, sandbox will
  have default resources.

## CreateSandboxFromSnapshotParams

```python
class CreateSandboxFromSnapshotParams(CreateSandboxBaseParams)
```

Parameters for creating a new Sandbox from a snapshot.

**Attributes**:

- `snapshot` _Optional[str]_ - Name of the snapshot to use for the Sandbox.

---

## File: src/content/docs/python-sdk/async/async-file-system.mdx

---
title: "AsyncFileSystem"
hideTitleOnPage: true
---

## AsyncFileSystem

```python
class AsyncFileSystem()
```

Provides file system operations within a Sandbox.

This class implements a high-level interface to file system operations that can
be performed within a Daytona Sandbox.

#### AsyncFileSystem.\_\_init\_\_

```python
def __init__(sandbox_id: str, toolbox_api: ToolboxApi,
             get_root_dir: Callable[[], Awaitable[str]])
```

Initializes a new FileSystem instance.

**Arguments**:

- `sandbox_id` _str_ - The Sandbox ID.
- `toolbox_api` _ToolboxApi_ - API client for Sandbox operations.
- `get_root_dir` _Callable[[], str]_ - A function to get the default root directory of the Sandbox.

#### AsyncFileSystem.create\_folder

```python
@intercept_errors(message_prefix="Failed to create folder: ")
async def create_folder(path: str, mode: str) -> None
```

Creates a new directory in the Sandbox at the specified path with the given
permissions.

**Arguments**:

- `path` _str_ - Path where the folder should be created. Relative paths are resolved based
  on the user's root directory.
- `mode` _str_ - Folder permissions in octal format (e.g., "755" for rwxr-xr-x).
  
**Example**:

```python
# Create a directory with standard permissions
await sandbox.fs.create_folder("workspace/data", "755")

# Create a private directory
await sandbox.fs.create_folder("workspace/secrets", "700")
```

#### AsyncFileSystem.delete\_file

```python
@intercept_errors(message_prefix="Failed to delete file: ")
async def delete_file(path: str) -> None
```

Deletes a file from the Sandbox.

**Arguments**:

- `path` _str_ - Absolute path to the file to delete.
  
**Example**:

```python
# Delete a file
await sandbox.fs.delete_file("workspace/data/old_file.txt")
```

#### AsyncFileSystem.download\_file

```python
@overload
async def download_file(remote_path: str, timeout: int = 30 * 60) -> bytes
```

Downloads a file from the Sandbox. Returns the file contents as a bytes object.
This method is useful when you want to load the file into memory without saving it to disk.
It can only be used for smaller files.

**Arguments**:

- `remote_path` _str_ - Path to the file in the Sandbox. Relative paths are resolved based on the user's
  root directory.
- `timeout` _int_ - Timeout for the download operation in seconds. 0 means no timeout. Default is 30 minutes.
  
**Returns**:

- `bytes` - The file contents as a bytes object.
  
**Example**:

```python
# Download and save a file locally
content = await sandbox.fs.download_file("workspace/data/file.txt")
with open("local_copy.txt", "wb") as f:
    f.write(content)

# Download and process text content
content = await sandbox.fs.download_file("workspace/data/config.json")
config = json.loads(content.decode('utf-8'))
```

#### AsyncFileSystem.download\_file

```python
@overload
async def download_file(remote_path: str,
                        local_path: str,
                        timeout: int = 30 * 60) -> None
```

Downloads a file from the Sandbox and saves it to a local file using stream.
This method is useful when you want to download larger files that may not fit into memory.

**Arguments**:

- `remote_path` _str_ - Path to the file in the Sandbox. Relative paths are resolved based on the user's
  root directory.
- `local_path` _str_ - Path to save the file locally.
- `timeout` _int_ - Timeout for the download operation in seconds. 0 means no timeout. Default is 30 minutes.
  
**Example**:

```python
local_path = "local_copy.txt"
await sandbox.fs.download_file("tmp/large_file.txt", local_path)
size_mb = os.path.getsize(local_path) / 1024 / 1024
print(f"Size of the downloaded file {local_path}: {size_mb} MB")
```

#### AsyncFileSystem.find\_files

```python
@intercept_errors(message_prefix="Failed to find files: ")
async def find_files(path: str, pattern: str) -> List[Match]
```

Searches for files containing a pattern, similar to
the grep command.

**Arguments**:

- `path` _str_ - Path to the file or directory to search. If the path is a directory,
  the search will be performed recursively. Relative paths are resolved based on the user's
  root directory.
- `pattern` _str_ - Search pattern to match against file contents.
  
**Returns**:

- `List[Match]` - List of matches found in files. Each Match object includes:
  - file: Path to the file containing the match
  - line: The line number where the match was found
  - content: The matching line content
  
**Example**:

```python
# Search for TODOs in Python files
matches = await sandbox.fs.find_files("workspace/src", "TODO:")
for match in matches:
    print(f"{match.file}:{match.line}: {match.content.strip()}")
```

#### AsyncFileSystem.get\_file\_info

```python
@intercept_errors(message_prefix="Failed to get file info: ")
async def get_file_info(path: str) -> FileInfo
```

Gets detailed information about a file or directory, including its
size, permissions, and timestamps.

**Arguments**:

- `path` _str_ - Path to the file or directory. Relative paths are resolved based on the user's
  root directory.
  
**Returns**:

- `FileInfo` - Detailed file information including:
  - name: File name
  - is_dir: Whether the path is a directory
  - size: File size in bytes
  - mode: File permissions
  - mod_time: Last modification timestamp
  - permissions: File permissions in octal format
  - owner: File owner
  - group: File group
  
**Example**:

```python
# Get file metadata
info = await sandbox.fs.get_file_info("workspace/data/file.txt")
print(f"Size: {info.size} bytes")
print(f"Modified: {info.mod_time}")
print(f"Mode: {info.mode}")

# Check if path is a directory
info = await sandbox.fs.get_file_info("workspace/data")
if info.is_dir:
    print("Path is a directory")
```

#### AsyncFileSystem.list\_files

```python
@intercept_errors(message_prefix="Failed to list files: ")
async def list_files(path: str) -> List[FileInfo]
```

Lists files and directories in a given path and returns their information, similar to the ls -l command.

**Arguments**:

- `path` _str_ - Path to the directory to list contents from. Relative paths are resolved based on the user's
  root directory.
  
**Returns**:

- `List[FileInfo]` - List of file and directory information. Each FileInfo
  object includes the same fields as described in get_file_info().
  
**Example**:

```python
# List directory contents
files = await sandbox.fs.list_files("workspace/data")

# Print files and their sizes
for file in files:
    if not file.is_dir:
        print(f"{file.name}: {file.size} bytes")

# List only directories
dirs = [f for f in files if f.is_dir]
print("Subdirectories:", ", ".join(d.name for d in dirs))
```

#### AsyncFileSystem.move\_files

```python
@intercept_errors(message_prefix="Failed to move files: ")
async def move_files(source: str, destination: str) -> None
```

Moves or renames a file or directory. The parent directory of the destination must exist.

**Arguments**:

- `source` _str_ - Path to the source file or directory. Relative paths are resolved based on the user's
  root directory.
- `destination` _str_ - Path to the destination. Relative paths are resolved based on the user's
  root directory.
  
**Example**:

```python
# Rename a file
await sandbox.fs.move_files(
    "workspace/data/old_name.txt",
    "workspace/data/new_name.txt"
)

# Move a file to a different directory
await sandbox.fs.move_files(
    "workspace/data/file.txt",
    "workspace/archive/file.txt"
)

# Move a directory
await sandbox.fs.move_files(
    "workspace/old_dir",
    "workspace/new_dir"
)
```

#### AsyncFileSystem.replace\_in\_files

```python
@intercept_errors(message_prefix="Failed to replace in files: ")
async def replace_in_files(files: List[str], pattern: str,
                           new_value: str) -> List[ReplaceResult]
```

Performs search and replace operations across multiple files.

**Arguments**:

- `files` _List[str]_ - List of file paths to perform replacements in. Relative paths are
  resolved based on the user's
  root directory.
- `pattern` _str_ - Pattern to search for.
- `new_value` _str_ - Text to replace matches with.
  
**Returns**:

- `List[ReplaceResult]` - List of results indicating replacements made in
  each file. Each ReplaceResult includes:
  - file: Path to the modified file
  - success: Whether the operation was successful
  - error: Error message if the operation failed
  
**Example**:

```python
# Replace in specific files
results = await sandbox.fs.replace_in_files(
    files=["workspace/src/file1.py", "workspace/src/file2.py"],
    pattern="old_function",
    new_value="new_function"
)

# Print results
for result in results:
    if result.success:
        print(f"{result.file}: {result.success}")
    else:
        print(f"{result.file}: {result.error}")
```

#### AsyncFileSystem.search\_files

```python
@intercept_errors(message_prefix="Failed to search files: ")
async def search_files(path: str, pattern: str) -> SearchFilesResponse
```

Searches for files and directories whose names match the
specified pattern. The pattern can be a simple string or a glob pattern.

**Arguments**:

- `path` _str_ - Path to the root directory to start search from. Relative paths are resolved based on the user's
  root directory.
- `pattern` _str_ - Pattern to match against file names. Supports glob
  patterns (e.g., "*.py" for Python files).
  
**Returns**:

- `SearchFilesResponse` - Search results containing:
  - files: List of matching file and directory paths
  
**Example**:

```python
# Find all Python files
result = await sandbox.fs.search_files("workspace", "*.py")
for file in result.files:
    print(file)

# Find files with specific prefix
result = await sandbox.fs.search_files("workspace/data", "test_*")
print(f"Found {len(result.files)} test files")
```

#### AsyncFileSystem.set\_file\_permissions

```python
@intercept_errors(message_prefix="Failed to set file permissions: ")
async def set_file_permissions(path: str,
                               mode: str = None,
                               owner: str = None,
                               group: str = None) -> None
```

Sets permissions and ownership for a file or directory. Any of the parameters can be None
to leave that attribute unchanged.

**Arguments**:

- `path` _str_ - Path to the file or directory. Relative paths are resolved based on the user's
  root directory.
- `mode` _Optional[str]_ - File mode/permissions in octal format
  (e.g., "644" for rw-r--r--).
- `owner` _Optional[str]_ - User owner of the file.
- `group` _Optional[str]_ - Group owner of the file.
  
**Example**:

```python
# Make a file executable
await sandbox.fs.set_file_permissions(
    path="workspace/scripts/run.sh",
    mode="755"  # rwxr-xr-x
)

# Change file owner
await sandbox.fs.set_file_permissions(
    path="workspace/data/file.txt",
    owner="daytona",
    group="daytona"
)
```

#### AsyncFileSystem.upload\_file

```python
@overload
async def upload_file(file: bytes,
                      remote_path: str,
                      timeout: int = 30 * 60) -> None
```

Uploads a file to the specified path in the Sandbox. If a file already exists at
the destination path, it will be overwritten. This method is useful when you want to upload
small files that fit into memory.

**Arguments**:

- `file` _bytes_ - File contents as a bytes object.
- `remote_path` _str_ - Path to the destination file. Relative paths are resolved based on the user's
  root directory.
- `timeout` _int_ - Timeout for the upload operation in seconds. 0 means no timeout. Default is 30 minutes.
  
**Example**:

```python
# Upload a text file
content = b"Hello, World!"
await sandbox.fs.upload_file(content, "tmp/hello.txt")

# Upload a local file
with open("local_file.txt", "rb") as f:
    content = f.read()
await sandbox.fs.upload_file(content, "tmp/file.txt")

# Upload binary data
import json
data = {"key": "value"}
content = json.dumps(data).encode('utf-8')
await sandbox.fs.upload_file(content, "tmp/config.json")
```

#### AsyncFileSystem.upload\_file

```python
@overload
async def upload_file(local_path: str,
                      remote_path: str,
                      timeout: int = 30 * 60) -> None
```

Uploads a file from the local file system to the specified path in the Sandbox.
If a file already exists at the destination path, it will be overwritten. This method uses
streaming to upload the file, so it is useful when you want to upload larger files that may
not fit into memory.

**Arguments**:

- `local_path` _str_ - Path to the local file to upload.
- `remote_path` _str_ - Path to the destination file in the Sandbox. Relative paths are
  resolved based on the user's root directory.
- `timeout` _int_ - Timeout for the upload operation in seconds. 0 means no timeout. Default is 30 minutes.
  
**Example**:

```python
await sandbox.fs.upload_file("local_file.txt", "tmp/large_file.txt")
```

#### AsyncFileSystem.upload\_files

```python
@intercept_errors(message_prefix="Failed to upload files: ")
async def upload_files(files: List[FileUpload],
                       timeout: int = 30 * 60) -> None
```

Uploads multiple files to the Sandbox. If files already exist at the destination paths,
they will be overwritten.

**Arguments**:

- `files` _List[FileUpload]_ - List of files to upload.
- `timeout` _int_ - Timeout for the upload operation in seconds. 0 means no timeout. Default is 30 minutes.

**Example**:

```python
# Upload multiple text files
files = [
    FileUpload(
        source=b"Content of file 1",
        destination="/tmp/file1.txt"
    ),
    FileUpload(
        source="workspace/data/file2.txt",
        destination="/tmp/file2.txt"
    ),
    FileUpload(
        source=b'{"key": "value"}',
        destination="/tmp/config.json"
    )
]
await sandbox.fs.upload_files(files)
```

## FileUpload

```python
@dataclass
class FileUpload()
```

Represents a file to be uploaded to the Sandbox.

**Attributes**:

- `source` _Union[bytes, str]_ - File contents as a bytes object or a local file path. If a bytes object is provided,
  make sure it fits into memory, otherwise use the local file path which content will be streamed to the Sandbox.
- `destination` _str_ - Absolute destination path in the Sandbox. Relative paths are resolved based on the user's
  root directory.

---

## File: src/content/docs/python-sdk/async/async-git.mdx

---
title: "AsyncGit"
hideTitleOnPage: true
---

## AsyncGit

```python
class AsyncGit()
```

Provides Git operations within a Sandbox.

**Example**:

```python
# Clone a repository
await sandbox.git.clone(
    url="https://github.com/user/repo.git",
    path="workspace/repo"
)

# Check repository status
status = await sandbox.git.status("workspace/repo")
print(f"Modified files: {status.modified}")

# Stage and commit changes
await sandbox.git.add("workspace/repo", ["file.txt"])
await sandbox.git.commit(
    path="workspace/repo",
    message="Update file",
    author="John Doe",
    email="john@example.com"
)
```

#### AsyncGit.\_\_init\_\_

```python
def __init__(sandbox_id: str, toolbox_api: ToolboxApi,
             get_root_dir: Callable[[], Awaitable[str]])
```

Initializes a new Git handler instance.

**Arguments**:

- `sandbox_id` _str_ - The Sandbox ID.
- `toolbox_api` _ToolboxApi_ - API client for Sandbox operations.
- `get_root_dir` _Callable[[], str]_ - A function to get the default root directory of the Sandbox.

#### AsyncGit.add

```python
@intercept_errors(message_prefix="Failed to add files: ")
async def add(path: str, files: List[str]) -> None
```

Stages the specified files for the next commit, similar to
running 'git add' on the command line.

**Arguments**:

- `path` _str_ - Path to the Git repository root. Relative paths are resolved based on the user's
  root directory.
- `files` _List[str]_ - List of file paths or directories to stage, relative to the repository root.
  
**Example**:

```python
# Stage a single file
await sandbox.git.add("workspace/repo", ["file.txt"])

# Stage multiple files
await sandbox.git.add("workspace/repo", [
    "src/main.py",
    "tests/test_main.py",
    "README.md"
])
```

#### AsyncGit.branches

```python
@intercept_errors(message_prefix="Failed to list branches: ")
async def branches(path: str) -> ListBranchResponse
```

Lists branches in the repository.

**Arguments**:

- `path` _str_ - Path to the Git repository root. Relative paths are resolved based on the user's
  root directory.
  
**Returns**:

- `ListBranchResponse` - List of branches in the repository.
  
**Example**:

```python
response = await sandbox.git.branches("workspace/repo")
print(f"Branches: {response.branches}")
```

#### AsyncGit.clone

```python
@intercept_errors(message_prefix="Failed to clone repository: ")
async def clone(url: str,
                path: str,
                branch: Optional[str] = None,
                commit_id: Optional[str] = None,
                username: Optional[str] = None,
                password: Optional[str] = None) -> None
```

Clones a Git repository into the specified path. It supports
cloning specific branches or commits, and can authenticate with the remote
repository if credentials are provided.

**Arguments**:

- `url` _str_ - Repository URL to clone from.
- `path` _str_ - Path where the repository should be cloned. Relative paths are resolved based on the user's
  root directory.
- `branch` _Optional[str]_ - Specific branch to clone. If not specified,
  clones the default branch.
- `commit_id` _Optional[str]_ - Specific commit to clone. If specified,
  the repository will be left in a detached HEAD state at this commit.
- `username` _Optional[str]_ - Git username for authentication.
- `password` _Optional[str]_ - Git password or token for authentication.
  
**Example**:

```python
# Clone the default branch
await sandbox.git.clone(
    url="https://github.com/user/repo.git",
    path="workspace/repo"
)

# Clone a specific branch with authentication
await sandbox.git.clone(
    url="https://github.com/user/private-repo.git",
    path="workspace/private",
    branch="develop",
    username="user",
    password="token"
)

# Clone a specific commit
await sandbox.git.clone(
    url="https://github.com/user/repo.git",
    path="workspace/repo-old",
    commit_id="abc123"
)
```

#### AsyncGit.commit

```python
@intercept_errors(message_prefix="Failed to commit changes: ")
async def commit(path: str, message: str, author: str,
                 email: str) -> GitCommitResponse
```

Creates a new commit with the staged changes. Make sure to stage
changes using the add() method before committing.

**Arguments**:

- `path` _str_ - Path to the Git repository root. Relative paths are resolved based on the user's
  root directory.
- `message` _str_ - Commit message describing the changes.
- `author` _str_ - Name of the commit author.
- `email` _str_ - Email address of the commit author.
  
**Example**:

```python
# Stage and commit changes
await sandbox.git.add("workspace/repo", ["README.md"])
await sandbox.git.commit(
    path="workspace/repo",
    message="Update documentation",
    author="John Doe",
    email="john@example.com"
)
```

#### AsyncGit.push

```python
@intercept_errors(message_prefix="Failed to push changes: ")
async def push(path: str,
               username: Optional[str] = None,
               password: Optional[str] = None) -> None
```

Pushes all local commits on the current branch to the remote
repository. If the remote repository requires authentication, provide
username and password/token.

**Arguments**:

- `path` _str_ - Path to the Git repository root. Relative paths are resolved based on the user's
  root directory.
- `username` _Optional[str]_ - Git username for authentication.
- `password` _Optional[str]_ - Git password or token for authentication.
  
**Example**:

```python
# Push without authentication (for public repos or SSH)
await sandbox.git.push("workspace/repo")

# Push with authentication
await sandbox.git.push(
    path="workspace/repo",
    username="user",
    password="github_token"
)
```

#### AsyncGit.pull

```python
@intercept_errors(message_prefix="Failed to pull changes: ")
async def pull(path: str,
               username: Optional[str] = None,
               password: Optional[str] = None) -> None
```

Pulls changes from the remote repository. If the remote repository requires authentication,
provide username and password/token.

**Arguments**:

- `path` _str_ - Path to the Git repository root. Relative paths are resolved based on the user's
  root directory.
- `username` _Optional[str]_ - Git username for authentication.
- `password` _Optional[str]_ - Git password or token for authentication.
  
**Example**:

```python
# Pull without authentication
await sandbox.git.pull("workspace/repo")

# Pull with authentication
await sandbox.git.pull(
    path="workspace/repo",
    username="user",
    password="github_token"
)
```

#### AsyncGit.status

```python
@intercept_errors(message_prefix="Failed to get status: ")
async def status(path: str) -> GitStatus
```

Gets the current Git repository status.

**Arguments**:

- `path` _str_ - Path to the Git repository root. Relative paths are resolved based on the user's
  root directory.
  
**Returns**:

- `GitStatus` - Repository status information including:
  - current_branch: Current branch name
  - file_status: List of file statuses
  - ahead: Number of local commits not pushed to remote
  - behind: Number of remote commits not pulled locally
  - branch_published: Whether the branch has been published to the remote repository
  
**Example**:

```python
status = await sandbox.git.status("workspace/repo")
print(f"On branch: {status.current_branch}")
print(f"Commits ahead: {status.ahead}")
print(f"Commits behind: {status.behind}")
```

## GitCommitResponse

```python
class GitCommitResponse()
```

Response from the git commit.

**Attributes**:

- `sha` _str_ - The SHA of the commit

---

## File: src/content/docs/python-sdk/async/async-lsp-server.mdx

---
title: "AsyncLspServer"
hideTitleOnPage: true
---

## AsyncLspServer

```python
class AsyncLspServer()
```

Provides Language Server Protocol functionality for code intelligence to provide
IDE-like features such as code completion, symbol search, and more.

#### AsyncLspServer.\_\_init\_\_

```python
def __init__(language_id: LspLanguageId, path_to_project: str,
             toolbox_api: ToolboxApi, sandbox_id: str)
```

Initializes a new LSP server instance.

**Arguments**:

- `language_id` _LspLanguageId_ - The language server type (e.g., LspLanguageId.TYPESCRIPT).
- `path_to_project` _str_ - Absolute path to the project root directory.
- `toolbox_api` _ToolboxApi_ - API client for Sandbox operations.
- `instance` _SandboxInstance_ - The Sandbox instance this server belongs to.

#### AsyncLspServer.start

```python
@intercept_errors(message_prefix="Failed to start LSP server: ")
async def start() -> None
```

Starts the language server.

This method must be called before using any other LSP functionality.
It initializes the language server for the specified language and project.

**Example**:

```python
lsp = sandbox.create_lsp_server("typescript", "workspace/project")
await lsp.start()  # Initialize the server
# Now ready for LSP operations
```

#### AsyncLspServer.stop

```python
@intercept_errors(message_prefix="Failed to stop LSP server: ")
async def stop() -> None
```

Stops the language server.

This method should be called when the LSP server is no longer needed to
free up system resources.

**Example**:

```python
# When done with LSP features
await lsp.stop()  # Clean up resources
```

#### AsyncLspServer.did\_open

```python
@intercept_errors(message_prefix="Failed to open file: ")
async def did_open(path: str) -> None
```

Notifies the language server that a file has been opened.

This method should be called when a file is opened in the editor to enable
language features like diagnostics and completions for that file. The server
will begin tracking the file's contents and providing language features.

**Arguments**:

- `path` _str_ - Path to the opened file. Relative paths are resolved based on the project path
  set in the LSP server constructor.
  
**Example**:

```python
# When opening a file for editing
await lsp.did_open("workspace/project/src/index.ts")
# Now can get completions, symbols, etc. for this file
```

#### AsyncLspServer.did\_close

```python
@intercept_errors(message_prefix="Failed to close file: ")
async def did_close(path: str) -> None
```

Notify the language server that a file has been closed.

This method should be called when a file is closed in the editor to allow
the language server to clean up any resources associated with that file.

**Arguments**:

- `path` _str_ - Path to the closed file. Relative paths are resolved based on the project path
  set in the LSP server constructor.
  
**Example**:

```python
# When done editing a file
await lsp.did_close("workspace/project/src/index.ts")
```

#### AsyncLspServer.document\_symbols

```python
@intercept_errors(message_prefix="Failed to get symbols from document: ")
async def document_symbols(path: str) -> List[LspSymbol]
```

Gets symbol information (functions, classes, variables, etc.) from a document.

**Arguments**:

- `path` _str_ - Path to the file to get symbols from. Relative paths are resolved based on the project path
  set in the LSP server constructor.
  
**Returns**:

- `List[LspSymbol]` - List of symbols in the document. Each symbol includes:
  - name: The symbol's name
  - kind: The symbol's kind (function, class, variable, etc.)
  - location: The location of the symbol in the file
  
**Example**:

```python
# Get all symbols in a file
symbols = await lsp.document_symbols("workspace/project/src/index.ts")
for symbol in symbols:
    print(f"{symbol.kind} {symbol.name}: {symbol.location}")
```

#### AsyncLspServer.workspace\_symbols

```python
@deprecated(
    reason=
    "Method is deprecated. Use `sandbox_symbols` instead. This method will be removed in a future version."
)
async def workspace_symbols(query: str) -> List[LspSymbol]
```

Searches for symbols matching the query string across all files
in the Sandbox.

**Arguments**:

- `query` _str_ - Search query to match against symbol names.
  
**Returns**:

- `List[LspSymbol]` - List of matching symbols from all files.

#### AsyncLspServer.sandbox\_symbols

```python
@intercept_errors(message_prefix="Failed to get symbols from sandbox: ")
async def sandbox_symbols(query: str) -> List[LspSymbol]
```

Searches for symbols matching the query string across all files
in the Sandbox.

**Arguments**:

- `query` _str_ - Search query to match against symbol names.
  
**Returns**:

- `List[LspSymbol]` - List of matching symbols from all files. Each symbol
  includes:
  - name: The symbol's name
  - kind: The symbol's kind (function, class, variable, etc.)
  - location: The location of the symbol in the file
  
**Example**:

```python
# Search for all symbols containing "User"
symbols = await lsp.sandbox_symbols("User")
for symbol in symbols:
    print(f"{symbol.name} in {symbol.location}")
```

#### AsyncLspServer.completions

```python
@intercept_errors(message_prefix="Failed to get completions: ")
async def completions(path: str, position: Position) -> CompletionList
```

Gets completion suggestions at a position in a file.

**Arguments**:

- `path` _str_ - Path to the file. Relative paths are resolved based on the project path
  set in the LSP server constructor.
- `position` _Position_ - Cursor position to get completions for.
  
**Returns**:

- `CompletionList` - List of completion suggestions. The list includes:
  - isIncomplete: Whether more items might be available
  - items: List of completion items, each containing:
  - label: The text to insert
  - kind: The kind of completion
  - detail: Additional details about the item
  - documentation: Documentation for the item
  - sortText: Text used to sort the item in the list
  - filterText: Text used to filter the item
  - insertText: The actual text to insert (if different from label)
  
**Example**:

```python
# Get completions at a specific position
pos = Position(line=10, character=15)
completions = await lsp.completions("workspace/project/src/index.ts", pos)
for item in completions.items:
    print(f"{item.label} ({item.kind}): {item.detail}")
```

## LspLanguageId

```python
class LspLanguageId(Enum)
```

Language IDs for Language Server Protocol (LSP).

**Enum Members**:
    - `PYTHON` ("python")
    - `TYPESCRIPT` ("typescript")
    - `JAVASCRIPT` ("javascript")

## Position

```python
class Position()
```

Represents a zero-based position in a text document,
specified by line number and character offset.

**Attributes**:

- `line` _int_ - Zero-based line number in the document.
- `character` _int_ - Zero-based character offset on the line.

#### Position.\_\_init\_\_

```python
def __init__(line: int, character: int)
```

Initialize a new Position instance.

**Arguments**:

- `line` _int_ - Zero-based line number in the document.
- `character` _int_ - Zero-based character offset on the line.

---

## File: src/content/docs/python-sdk/async/async-object-storage.mdx

---
title: "AsyncObjectStorage"
hideTitleOnPage: true
---

## AsyncObjectStorage

```python
class AsyncObjectStorage()
```

AsyncObjectStorage class for interacting with object storage services.

**Attributes**:

- `endpoint_url` _str_ - The endpoint URL for the object storage service.
- `aws_access_key_id` _str_ - The access key ID for the object storage service.
- `aws_secret_access_key` _str_ - The secret access key for the object storage service.
- `aws_session_token` _str_ - The session token for the object storage service. Used for temporary credentials.
- `bucket_name` _str_ - The name of the bucket to use.

#### AsyncObjectStorage.upload

```python
async def upload(path, organization_id, archive_base_path=None) -> str
```

Uploads a file to the object storage service.

**Arguments**:

- `path` _str_ - The path to the file to upload.
- `organization_id` _str_ - The organization ID to use.
- `archive_base_path` _str_ - The base path to use for the archive.

---

## File: src/content/docs/python-sdk/async/async-sandbox.mdx

---
title: "AsyncSandbox"
hideTitleOnPage: true
---

## AsyncSandbox

```python
class AsyncSandbox(SandboxDto)
```

Represents a Daytona Sandbox.

**Attributes**:

- `fs` _AsyncFileSystem_ - File system operations interface.
- `git` _AsyncGit_ - Git operations interface.
- `process` _AsyncProcess_ - Process execution interface.
- `id` _str_ - Unique identifier for the Sandbox.
- `organization_id` _str_ - Organization ID of the Sandbox.
- `snapshot` _str_ - Daytona snapshot used to create the Sandbox.
- `user` _str_ - OS user running in the Sandbox.
- `env` _Dict[str, str]_ - Environment variables set in the Sandbox.
- `labels` _Dict[str, str]_ - Custom labels attached to the Sandbox.
- `public` _bool_ - Whether the Sandbox is publicly accessible.
- `target` _str_ - Target location of the runner where the Sandbox runs.
- `cpu` _int_ - Number of CPUs allocated to the Sandbox.
- `gpu` _int_ - Number of GPUs allocated to the Sandbox.
- `memory` _int_ - Amount of memory allocated to the Sandbox in GiB.
- `disk` _int_ - Amount of disk space allocated to the Sandbox in GiB.
- `state` _SandboxState_ - Current state of the Sandbox (e.g., "started", "stopped").
- `error_reason` _str_ - Error message if Sandbox is in error state.
- `backup_state` _SandboxBackupStateEnum_ - Current state of Sandbox backup.
- `backup_created_at` _str_ - When the backup was created.
- `auto_stop_interval` _int_ - Auto-stop interval in minutes.
- `auto_archive_interval` _int_ - Auto-archive interval in minutes.
- `runner_domain` _str_ - Domain name of the Sandbox runner.
- `volumes` _List[str]_ - Volumes attached to the Sandbox.
- `build_info` _str_ - Build information for the Sandbox if it was created from dynamic build.
- `created_at` _str_ - When the Sandbox was created.
- `updated_at` _str_ - When the Sandbox was last updated.

#### AsyncSandbox.\_\_init\_\_

```python
def __init__(sandbox_dto: SandboxDto, sandbox_api: SandboxApi,
             toolbox_api: ToolboxApi, code_toolbox: SandboxCodeToolbox)
```

Initialize a new Sandbox instance.

**Arguments**:

- `id` _str_ - Unique identifier for the Sandbox.
- `instance` _SandboxInstance_ - The underlying Sandbox instance.
- `sandbox_api` _SandboxApi_ - API client for Sandbox operations.
- `toolbox_api` _ToolboxApi_ - API client for toolbox operations.
- `code_toolbox` _SandboxCodeToolbox_ - Language-specific toolbox implementation.

#### AsyncSandbox.refresh\_data

```python
async def refresh_data() -> None
```

Refreshes the Sandbox data from the API.

**Example**:

```python
await sandbox.refresh_data()
print(f"Sandbox {sandbox.id}:")
print(f"State: {sandbox.state}")
print(f"Resources: {sandbox.cpu} CPU, {sandbox.memory} GiB RAM")
```

#### AsyncSandbox.get\_user\_root\_dir

```python
@intercept_errors(message_prefix="Failed to get sandbox root directory: ")
async def get_user_root_dir() -> str
```

Gets the root directory path for the logged in user inside the Sandbox.

**Returns**:

- `str` - The absolute path to the Sandbox root directory for the logged in user.
  
**Example**:

```python
root_dir = await sandbox.get_user_root_dir()
print(f"Sandbox root: {root_dir}")
```

#### AsyncSandbox.create\_lsp\_server

```python
def create_lsp_server(language_id: LspLanguageId,
                      path_to_project: str) -> AsyncLspServer
```

Creates a new Language Server Protocol (LSP) server instance.

The LSP server provides language-specific features like code completion,
diagnostics, and more.

**Arguments**:

- `language_id` _LspLanguageId_ - The language server type (e.g., LspLanguageId.PYTHON).
- `path_to_project` _str_ - Path to the project root directory. Relative paths are resolved based on the user's
  root directory.
  
**Returns**:

- `LspServer` - A new LSP server instance configured for the specified language.
  
**Example**:

```python
lsp = sandbox.create_lsp_server("python", "workspace/project")
```

#### AsyncSandbox.set\_labels

```python
@intercept_errors(message_prefix="Failed to set labels: ")
async def set_labels(labels: Dict[str, str]) -> Dict[str, str]
```

Sets labels for the Sandbox.

Labels are key-value pairs that can be used to organize and identify Sandboxes.

**Arguments**:

- `labels` _Dict[str, str]_ - Dictionary of key-value pairs representing Sandbox labels.
  
**Returns**:

  Dict[str, str]: Dictionary containing the updated Sandbox labels.
  
**Example**:

```python
new_labels = sandbox.set_labels({
    "project": "my-project",
    "environment": "development",
    "team": "backend"
})
print(f"Updated labels: {new_labels}")
```

#### AsyncSandbox.start

```python
@intercept_errors(message_prefix="Failed to start sandbox: ")
@with_timeout(error_message=lambda self, timeout: (
    f"Sandbox {self.id} failed to start within the {timeout} seconds timeout period"
))
async def start(timeout: Optional[float] = 60)
```

Starts the Sandbox and waits for it to be ready.

**Arguments**:

- `timeout` _Optional[float]_ - Maximum time to wait in seconds. 0 means no timeout. Default is 60 seconds.
  
**Raises**:

- `DaytonaError` - If timeout is negative. If sandbox fails to start or times out.
  
**Example**:

```python
sandbox = daytona.get_current_sandbox("my-sandbox")
sandbox.start(timeout=40)  # Wait up to 40 seconds
print("Sandbox started successfully")
```

#### AsyncSandbox.stop

```python
@intercept_errors(message_prefix="Failed to stop sandbox: ")
@with_timeout(error_message=lambda self, timeout: (
    f"Sandbox {self.id} failed to stop within the {timeout} seconds timeout period"
))
async def stop(timeout: Optional[float] = 60)
```

Stops the Sandbox and waits for it to be fully stopped.

**Arguments**:

- `timeout` _Optional[float]_ - Maximum time to wait in seconds. 0 means no timeout. Default is 60 seconds.
  
**Raises**:

- `DaytonaError` - If timeout is negative; If sandbox fails to stop or times out
  
**Example**:

```python
sandbox = daytona.get_current_sandbox("my-sandbox")
sandbox.stop()
print("Sandbox stopped successfully")
```

#### AsyncSandbox.delete

```python
async def delete() -> None
```

Deletes the Sandbox.

#### AsyncSandbox.wait\_for\_sandbox\_start

```python
@intercept_errors(
    message_prefix="Failure during waiting for sandbox to start: ")
@with_timeout(error_message=lambda self, timeout: (
    f"Sandbox {self.id} failed to become ready within the {timeout} seconds timeout period"
))
async def wait_for_sandbox_start(timeout: Optional[float] = 60) -> None
```

Waits for the Sandbox to reach the 'started' state. Polls the Sandbox status until it
reaches the 'started' state, encounters an error or times out.

**Arguments**:

- `timeout` _Optional[float]_ - Maximum time to wait in seconds. 0 means no timeout. Default is 60 seconds.
  
**Raises**:

- `DaytonaError` - If timeout is negative; If Sandbox fails to start or times out

#### AsyncSandbox.wait\_for\_sandbox\_stop

```python
@intercept_errors(
    message_prefix="Failure during waiting for sandbox to stop: ")
@with_timeout(error_message=lambda self, timeout: (
    f"Sandbox {self.id} failed to become stopped within the {timeout} seconds timeout period"
))
async def wait_for_sandbox_stop(timeout: Optional[float] = 60) -> None
```

Waits for the Sandbox to reach the 'stopped' state. Polls the Sandbox status until it
reaches the 'stopped' state, encounters an error or times out. It will wait up to 60 seconds
for the Sandbox to stop.

**Arguments**:

- `timeout` _Optional[float]_ - Maximum time to wait in seconds. 0 means no timeout. Default is 60 seconds.
  
**Raises**:

- `DaytonaError` - If timeout is negative. If Sandbox fails to stop or times out.

#### AsyncSandbox.set\_autostop\_interval

```python
@intercept_errors(message_prefix="Failed to set auto-stop interval: ")
async def set_autostop_interval(interval: int) -> None
```

Sets the auto-stop interval for the Sandbox.

The Sandbox will automatically stop after being idle (no new events) for the specified interval.
Events include any state changes or interactions with the Sandbox through the SDK.
Interactions using Sandbox Previews are not included.

**Arguments**:

- `interval` _int_ - Number of minutes of inactivity before auto-stopping.
  Set to 0 to disable auto-stop. Defaults to 15.
  
**Raises**:

- `DaytonaError` - If interval is negative
  
**Example**:

```python
# Auto-stop after 1 hour
sandbox.set_autostop_interval(60)
# Or disable auto-stop
sandbox.set_autostop_interval(0)
```

#### AsyncSandbox.set\_auto\_archive\_interval

```python
@intercept_errors(message_prefix="Failed to set auto-archive interval: ")
async def set_auto_archive_interval(interval: int) -> None
```

Sets the auto-archive interval for the Sandbox.

The Sandbox will automatically archive after being continuously stopped for the specified interval.

**Arguments**:

- `interval` _int_ - Number of minutes after which a continuously stopped Sandbox will be auto-archived.
  Set to 0 for the maximum interval. Default is 7 days.
  
**Raises**:

- `DaytonaError` - If interval is negative
  
**Example**:

```python
# Auto-archive after 1 hour
sandbox.set_autoarchive_interval(60)
# Or use the maximum interval
sandbox.set_autoarchive_interval(0)
```

#### AsyncSandbox.get\_preview\_link

```python
@intercept_errors(message_prefix="Failed to get preview link: ")
async def get_preview_link(port: int) -> PortPreviewUrl
```

Retrieves the preview link for the sandbox at the specified port. If the port is closed,
it will be opened automatically. For private sandboxes, a token is included to grant access
to the URL.

**Arguments**:

- `port` _int_ - The port to open the preview link on.
  
**Returns**:

- `PortPreviewUrl` - The response object for the preview link, which includes the `url`
  and the `token` (to access private sandboxes).
  
**Example**:

```python
preview_link = sandbox.get_preview_link(3000)
print(f"Preview URL: {preview_link.url}")
print(f"Token: {preview_link.token}")
```

#### AsyncSandbox.archive

```python
@intercept_errors(message_prefix="Failed to archive sandbox: ")
async def archive() -> None
```

Archives the sandbox, making it inactive and preserving its state. When sandboxes are
archived, the entire filesystem state is moved to cost-effective object storage, making it
possible to keep sandboxes available for an extended period. The tradeoff between archived
and stopped states is that starting an archived sandbox takes more time, depending on its size.
Sandbox must be stopped before archiving.

## Resources

```python
@dataclass
class Resources()
```

Resources configuration for Sandbox.

**Attributes**:

- `cpu` _Optional[int]_ - Number of CPU cores to allocate.
- `memory` _Optional[int]_ - Amount of memory in GiB to allocate.
- `disk` _Optional[int]_ - Amount of disk space in GiB to allocate.
- `gpu` _Optional[int]_ - Number of GPUs to allocate.
  
**Example**:

```python
resources = Resources(
    cpu=2,
    memory=4,  # 4GiB RAM
    disk=20,   # 20GiB disk
    gpu=1
)
params = CreateSandboxFromImageParams(
    image=Image.debian_slim("3.12").pip_install(["numpy", "pandas"]),
    language="python",
    resources=resources
)
```