1. Project Overview & Quickstart (daytonaio/daytona)
[!IMPORTANT]
This repository is no longer maintained.As of June 2026, Daytona's core development has moved to a private codebase. This repository will receive no further updates, fixes, or releases.
It remains public and free to use, fork, and build on under the LICENSE, as is and without support or warranty.Daytona resources are available at github.com/daytona.
Run AI Code.
Secure and Elastic Infrastructure for
Running Your AI-Generated Code.
Daytona is a secure and elastic infrastructure runtime for AI-generated code execution and agent workflows. Our open-source platform provides sandboxes, full composable computers with complete isolation, a dedicated kernel, filesystem, network stack, and allocated vCPU, RAM, and disk.
Sandboxes are the core component of the Daytona platform, spinning up in under 90ms from code to execution and running any code in Python, TypeScript, and JavaScript. Built on OCI/Docker compatibility, massive parallelization, and unlimited persistence, sandboxes deliver consistent, predictable environments for agent workflows.
Agents and developers interact with sandboxes programmatically using the Daytona SDKs, API, and CLI. Operations span sandbox lifecycle management, filesystem operations, process and code execution, and runtime configuration through base images, packages, and tooling. Our stateful environment snapshots enable persistent agent operations across sessions, making Daytona the ideal foundation for AI agent architectures.
Features
Daytona provides an extensive set of features and tools for interacting with sandboxes.
- Platform: governance and operational controls for organizations standardizing on Daytona
- Sandboxes: isolated full composable computers that execute workloads and retain state
- Agent tools: programmatic capabilities for application code, agents, and integrations
- Human tools: interfaces and remote sessions for interacting with sandboxes
- System tools: platform-level hooks and controls for lifecycle events and network access
Architecture
Daytona platform is organized into multiple plane components, each serving a specific purpose. A detailed overview of each component is available in the architecture documentation.
- Interface plane: provides client interfaces for interacting with Daytona
- Control plane: orchestrates all sandbox operations
- Compute plane: runs and manages sandbox instances
Client libraries
Client libraries integrate the Daytona platform from application code through developer-facing SDKs backed by OpenAPI-generated REST clients and toolbox API clients. Each directory is a publishable package for a specific language or runtime, available in the libs directory.
Python
pip install daytonaStandalone packages and libraries for interacting with Daytona using Python:
sdk-pythonโขapi-client-pythonโขapi-client-python-asyncโขtoolbox-api-client-pythonโขtoolbox-api-client-python-async
TypeScript
npm install @daytona/sdkStandalone packages and libraries for interacting with Daytona using TypeScript:
Ruby
gem install daytonaStandalone packages and libraries for interacting with Daytona using Ruby:
Go
go get github.com/daytonaio/daytona/libs/sdk-goStandalone packages and libraries for interacting with Daytona using Go:
sdk-goโขapi-client-goโขtoolbox-api-client-go
Java
Gradle (build.gradle.kts):
dependencies {
implementation("io.daytona:sdk:x.y.z")
}Maven (pom.xml):
<dependency>
<groupId>io.daytona</groupId>
<artifactId>sdk</artifactId>
<version>x.y.z</version>
</dependency>Standalone packages and libraries for interacting with Daytona using Java:
Quick Start
- Create an account at app.daytona.io
- Generate an API key
- Create a sandbox
Python SDK
from daytona import Daytona, DaytonaConfig
config = DaytonaConfig(api_key="YOUR_API_KEY")
daytona = Daytona(config)
sandbox = daytona.create()
response = sandbox.process.code_run('print("Hello World!")')
print(response.result)Typescript SDK
import { Daytona } from "@daytona/sdk";
const daytona = new Daytona({ apiKey: "YOUR_API_KEY" });
const sandbox = await daytona.create();
const response = await sandbox.process.codeRun('print("Hello World!")');
console.log(response.result);Ruby SDK
require 'daytona'
config = Daytona::Config.new(api_key: 'YOUR_API_KEY')
daytona = Daytona::Daytona.new(config)
sandbox = daytona.create
response = sandbox.process.code_run(code: 'print("Hello World!")')
puts response.resultGo SDK
package main
import (
"context"
"fmt"
"github.com/daytonaio/daytona/libs/sdk-go/pkg/daytona"
"github.com/daytonaio/daytona/libs/sdk-go/pkg/types"
)
func main() {
config := &types.DaytonaConfig{APIKey: "YOUR_API_KEY"}
client, _ := daytona.NewClientWithConfig(config)
ctx := context.Background()
sandbox, _ := client.Create(ctx, nil)
response, _ := sandbox.Process.ExecuteCommand(ctx, "echo 'Hello World!'")
fmt.Println(response.Result)
}Java SDK
import io.daytona.sdk.Daytona;
import io.daytona.sdk.DaytonaConfig;
import io.daytona.sdk.Sandbox;
import io.daytona.sdk.model.ExecuteResponse;
public class Main {
public static void main(String[] args) {
DaytonaConfig config = new DaytonaConfig.Builder()
.apiKey("YOUR_API_KEY")
.build();
try (Daytona daytona = new Daytona(config)) {
Sandbox sandbox = daytona.create();
ExecuteResponse response = sandbox.getProcess().executeCommand("echo 'Hello World!'");
System.out.println(response.getResult());
}
}
}API
curl 'https://app.daytona.io/api/sandbox' \
--request POST \
--header 'Authorization: Bearer <YOUR_API_KEY>' \
--header 'Content-Type: application/json' \
--data '{}'CLI
daytona create2. Official Technical Reference & Guides (daytonaio/docs)
File: README.md
Contents of this repository were transferred to the [Daytona](https://github.com/daytonaio/daytona) repo.
Daytona Documentation
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:
git clone https://github.com/daytonaio/docs.gityarn installUseful 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 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:
HomeOverview of Daytona's SDK interfaces and quick start instructions.
Getting StartedInstructions for installing Daytona across various environments.
ConfigurationGuides to configuring Daytona's core options.
ManagementPractical instructions for managing Daytona sandboxes.
Agent ToolboxInformation 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. If you would like to contribute to the software, you must:
- Read the Developer Certificate of Origin Version 1.1 (https://developercertificate.org/)
- 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. 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. For more information see the Code of Conduct or contact [email protected]. with any additional questions or comments.
Questions
If you need guidance on contributing to Daytona, talk to us on
Slack.
File: src/content/docs/python-sdk/common/charts.mdx
title: "Charts" hideTitleOnPage: true
Chart
class Chart()Represents a chart with metadata from matplotlib.
Attributes:
typeChartType - The type of charttitlestr - The title of the chartelementsList[Any] - The elements of the chartpngOptional[str] - The PNG representation of the chart encoded in base64
ChartType
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
class Chart2D(Chart)Represents a 2D chart with metadata.
Attributes:
x_labelOptional[str] - The label of the x-axisy_labelOptional[str] - The label of the y-axis
PointData
class PointData()Represents a point in a 2D chart.
Attributes:
labelstr - The label of the pointpointsList[Tuple[Union[str, float], Union[str, float]]] - The points of the chart
PointChart
class PointChart(Chart2D)Represents a point chart with metadata.
Attributes:
x_ticksList[Union[str, float]] - The ticks of the x-axisx_tick_labelsList[str] - The labels of the x-axisx_scalestr - The scale of the x-axisy_ticksList[Union[str, float]] - The ticks of the y-axisy_tick_labelsList[str] - The labels of the y-axisy_scalestr - The scale of the y-axiselementsList[PointData] - The points of the chart
LineChart
class LineChart(PointChart)Represents a line chart with metadata.
Attributes:
typeChartType - The type of chart
ScatterChart
class ScatterChart(PointChart)Represents a scatter chart with metadata.
Attributes:
typeChartType - The type of chart
BarData
class BarData()Represents a bar in a bar chart.
Attributes:
labelstr - The label of the bargroupstr - The group of the barvaluestr - The value of the bar
BarChart
class BarChart(Chart2D)Represents a bar chart with metadata.
Attributes:
typeChartType - The type of chartelementsList[BarData] - The bars of the chart
PieData
class PieData()Represents a pie slice in a pie chart.
Attributes:
labelstr - The label of the pie sliceanglefloat - The angle of the pie sliceradiusfloat - The radius of the pie sliceautopctfloat - The autopct value of the pie slice
PieChart
class PieChart(Chart)Represents a pie chart with metadata.
Attributes:
typeChartType - The type of chartelementsList[PieData] - The pie slices of the chart
BoxAndWhiskerData
class BoxAndWhiskerData()Represents a box and whisker in a box and whisker chart.
Attributes:
labelstr - The label of the box and whiskerminfloat - The minimum value of the box and whiskerfirst_quartilefloat - The first quartile of the box and whiskermedianfloat - The median of the box and whiskerthird_quartilefloat - The third quartile of the box and whiskermaxfloat - The maximum value of the box and whiskeroutliersList[float] - The outliers of the box and whisker
BoxAndWhiskerChart
class BoxAndWhiskerChart(Chart2D)Represents a box and whisker chart with metadata.
Attributes:
typeChartType - The type of chartelementsList[BoxAndWhiskerData] - The box and whiskers of the chart
CompositeChart
class CompositeChart(Chart)Represents a composite chart with metadata. A composite chart is a chart
that contains multiple charts (subplots).
Attributes:
typeChartType - The type of chartelementsList[Chart] - The charts (subplots) of the composite chart
File: src/content/docs/python-sdk/common/errors.mdx
title: "Errors" hideTitleOnPage: true
DaytonaError
class DaytonaError(Exception)Base error for Daytona SDK.
File: src/content/docs/python-sdk/common/image.mdx
title: "Image" hideTitleOnPage: true
Image
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
def dockerfile() -> strReturns a generated Dockerfile for the image.
Image.pip\_install
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:
image = Image.debian_slim("3.12").pip_install("requests", "pandas")Image.pip\_install\_from\_requirements
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:
image = Image.debian_slim("3.12").pip_install_from_requirements("requirements.txt")Image.pip\_install\_from\_pyproject
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:
image = Image.debian_slim("3.12") .pip_install_from_pyproject("pyproject.toml", optional_dependencies=["dev"])Image.add\_local\_file
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:
image = Image.debian_slim("3.12").add_local_file("package.json", "/home/daytona/package.json")Image.add\_local\_dir
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:
image = Image.debian_slim("3.12").add_local_dir("src", "/home/daytona/src")Image.run\_commands
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:
image = Image.debian_slim("3.12").run_commands(
'echo "Hello, world!"',
['bash', '-c', 'echo Hello, world, again!']
)Image.env
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:
image = Image.debian_slim("3.12").env({"PROJECT_ROOT": "/home/daytona"})Image.workdir
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:
image = Image.debian_slim("3.12").workdir("/home/daytona")Image.entrypoint
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:
image = Image.debian_slim("3.12").entrypoint(["/bin/bash"])Image.cmd
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:
image = Image.debian_slim("3.12").cmd(["/bin/bash"])Image.dockerfile\_commands
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:
image = Image.debian_slim("3.12").dockerfile_commands(["RUN echo 'Hello, world!'"])Image.from\_dockerfile
@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:
image = Image.from_dockerfile("Dockerfile")Image.base
@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:
image = Image.base("python:3.12-slim-bookworm")Image.debian\_slim
@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:
image = Image.debian_slim("3.12")Context
class Context(BaseModel)Context for an image.
Attributes:
source_pathstr - The path to the source file or directory.archive_pathOptional[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
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:
volumeAsyncVolumeService - Service for managing volumes.snapshotAsyncSnapshotService - Service for managing snapshots.
Example:
Using environment variables:
async with AsyncDaytona() as daytona: # Uses DAYTONA_API_KEY, DAYTONA_API_URL
sandbox = await daytona.create()Using explicit configuration:
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\_\_
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 authenticationDAYTONA_API_URL: Required api URLDAYTONA_TARGET: Optional target environment (defaults to 'us')
Arguments:
configOptional[DaytonaConfig] - Object containing api_key, api_url, and target.
Raises:
DaytonaError- If API key is not provided either through config or environment variables
Example:
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\_\_
async def __aenter__()Async context manager entry.
AsyncDaytona.\_\_aexit\_\_
async def __aexit__(exc_type, exc_value, traceback)Async context manager exit - ensures proper cleanup.
AsyncDaytona.close
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:
daytona = AsyncDaytona()
try:
sandbox = await daytona.create()
# ... use sandbox ...
finally:
await daytona.close()Or better yet, use as async context manager:
async with AsyncDaytona() as daytona:
sandbox = await daytona.create()
# ... use sandbox ...
# Automatically closedAsyncDaytona.create
@overload
async def create(params: Optional[CreateSandboxFromSnapshotParams] = None,
*,
timeout: Optional[float] = 60) -> AsyncSandboxCreates Sandboxes from specified or default snapshot. You can specify various parameters,
including language, image, environment variables, and volumes.
Arguments:
paramsOptional[CreateSandboxFromSnapshotParams] - Parameters for Sandbox creation. If not provided,
defaults to default Daytona snapshot and Python language.timeoutOptional[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:
sandbox = await daytona.create()Create a custom Sandbox:
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
@overload
async def create(
params: Optional[CreateSandboxFromImageParams] = None,
*,
timeout: Optional[float] = 60,
on_snapshot_create_logs: Callable[[str], None] = None) -> AsyncSandboxCreates 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:
paramsOptional[CreateSandboxFromImageParams] - Parameters for Sandbox creation from image.timeoutOptional[float] - Timeout (in seconds) for sandbox creation. 0 means no timeout.
Default is 60 seconds.on_snapshot_create_logsCallable[[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:
sandbox = await daytona.create(CreateSandboxFromImageParams(image="debian:12.9"))Create a custom Sandbox from declarative Image definition:
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
@intercept_errors(message_prefix="Failed to remove sandbox: ")
async def delete(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> NoneDeletes a Sandbox.
Arguments:
sandboxSandbox - The Sandbox instance to delete.timeoutOptional[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:
sandbox = await daytona.create()
# ... use sandbox ...
await daytona.delete(sandbox) # Clean up when doneAsyncDaytona.get
@intercept_errors(message_prefix="Failed to get sandbox: ")
async def get(sandbox_id: str) -> AsyncSandboxGets a Sandbox by its ID.
Arguments:
sandbox_idstr - The ID of the Sandbox to retrieve.
Returns:
Sandbox- The Sandbox instance.
Raises:
DaytonaError- If sandbox_id is not provided.
Example:
sandbox = await daytona.get("my-sandbox-id")
print(sandbox.status)AsyncDaytona.find\_one
@intercept_errors(message_prefix="Failed to find sandbox: ")
async def find_one(sandbox_id: Optional[str] = None,
labels: Optional[Dict[str, str]] = None) -> AsyncSandboxFinds a Sandbox by its ID or labels.
Arguments:
sandbox_idOptional[str] - The ID of the Sandbox to retrieve.labelsOptional[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:
sandbox = await daytona.find_one(labels={"my-label": "my-value"})
print(f"Sandbox ID: {sandbox.id} State: {sandbox.state}")AsyncDaytona.list
@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:
labelsOptional[Dict[str, str]] - Labels to filter Sandboxes.
Returns:
List[Sandbox]- List of Sandbox instances that match the labels.
Example:
sandboxes = await daytona.list(labels={"my-label": "my-value"})
for sandbox in sandboxes:
print(f"{sandbox.id}: {sandbox.status}")AsyncDaytona.start
async def start(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> NoneStarts a Sandbox and waits for it to be ready.
Arguments:
sandboxSandbox - The Sandbox to start.timeoutOptional[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
async def stop(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> NoneStops a Sandbox and waits for it to be stopped.
Arguments:
sandboxSandbox - The sandbox to stoptimeoutOptional[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
@dataclass
class CodeLanguage(Enum)Programming languages supported by Daytona
Enum Members:
- PYTHON ("python")
- TYPESCRIPT ("typescript")
- JAVASCRIPT ("javascript")
DaytonaConfig
class DaytonaConfig(BaseModel)Configuration options for initializing the Daytona client.
Attributes:
api_keyOptional[str] - API key for authentication with the Daytona API. If not set, it must be provided
via the environment variableDAYTONA_API_KEY, or a JWT token must be provided instead.jwt_tokenOptional[str] - JWT token for authentication with the Daytona API. If not set, it must be provided
via the environment variableDAYTONA_JWT_TOKEN, or an API key must be provided instead.organization_idOptional[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 variableDAYTONA_ORGANIZATION_ID.api_urlOptional[str] - URL of the Daytona API. Defaults to'https://app.daytona.io/api'if not set
here or in the environment variableDAYTONA_API_URL.server_urlOptional[str] - Deprecated. Useapi_urlinstead. This property will be removed
in a future version.targetOptional[SandboxTargetRegion] - Target environment for the Sandbox. Defaults to'us'if not set here
or in the environment variableDAYTONA_TARGET.
Example:
config = DaytonaConfig(api_key="your-api-key")config = DaytonaConfig(jwt_token="your-jwt-token", organization_id="your-organization-id")CreateSandboxBaseParams
class CreateSandboxBaseParams(BaseModel)Base parameters for creating a new Sandbox.
Attributes:
languageOptional[CodeLanguage] - Programming language for the Sandbox. Defaults to "python".os_userOptional[str] - OS user for the Sandbox.env_varsOptional[Dict[str, str]] - Environment variables to set in the Sandbox.labelsOptional[Dict[str, str]] - Custom labels for the Sandbox.publicOptional[bool] - Whether the Sandbox should be public.timeoutOptional[float] - Timeout in seconds for Sandbox to be created and started.auto_stop_intervalOptional[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_intervalOptional[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
class CreateSandboxFromImageParams(CreateSandboxBaseParams)Parameters for creating a new Sandbox from an image.
Attributes:
imageUnion[str, Image] - Custom Docker image to use for the Sandbox. If an Image object is provided,
the image will be dynamically built.resourcesOptional[Resources] - Resource configuration for the Sandbox. If not provided, sandbox will
have default resources.
CreateSandboxFromSnapshotParams
class CreateSandboxFromSnapshotParams(CreateSandboxBaseParams)Parameters for creating a new Sandbox from a snapshot.
Attributes:
snapshotOptional[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
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\_\_
def __init__(sandbox_id: str, toolbox_api: ToolboxApi,
get_root_dir: Callable[[], Awaitable[str]])Initializes a new FileSystem instance.
Arguments:
sandbox_idstr - The Sandbox ID.toolbox_apiToolboxApi - API client for Sandbox operations.get_root_dirCallable[[], str] - A function to get the default root directory of the Sandbox.
AsyncFileSystem.create\_folder
@intercept_errors(message_prefix="Failed to create folder: ")
async def create_folder(path: str, mode: str) -> NoneCreates a new directory in the Sandbox at the specified path with the given
permissions.
Arguments:
pathstr - Path where the folder should be created. Relative paths are resolved based
on the user's root directory.modestr - Folder permissions in octal format (e.g., "755" for rwxr-xr-x).
Example:
# 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
@intercept_errors(message_prefix="Failed to delete file: ")
async def delete_file(path: str) -> NoneDeletes a file from the Sandbox.
Arguments:
pathstr - Absolute path to the file to delete.
Example:
# Delete a file
await sandbox.fs.delete_file("workspace/data/old_file.txt")AsyncFileSystem.download\_file
@overload
async def download_file(remote_path: str, timeout: int = 30 * 60) -> bytesDownloads 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_pathstr - Path to the file in the Sandbox. Relative paths are resolved based on the user's
root directory.timeoutint - 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:
# 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
@overload
async def download_file(remote_path: str,
local_path: str,
timeout: int = 30 * 60) -> NoneDownloads 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_pathstr - Path to the file in the Sandbox. Relative paths are resolved based on the user's
root directory.local_pathstr - Path to save the file locally.timeoutint - Timeout for the download operation in seconds. 0 means no timeout. Default is 30 minutes.
Example:
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
@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:
pathstr - 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.patternstr - 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:
# 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
@intercept_errors(message_prefix="Failed to get file info: ")
async def get_file_info(path: str) -> FileInfoGets detailed information about a file or directory, including its
size, permissions, and timestamps.
Arguments:
pathstr - 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:
# 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
@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:
pathstr - 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:
# 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
@intercept_errors(message_prefix="Failed to move files: ")
async def move_files(source: str, destination: str) -> NoneMoves or renames a file or directory. The parent directory of the destination must exist.
Arguments:
sourcestr - Path to the source file or directory. Relative paths are resolved based on the user's
root directory.destinationstr - Path to the destination. Relative paths are resolved based on the user's
root directory.
Example:
# 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
@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:
filesList[str] - List of file paths to perform replacements in. Relative paths are
resolved based on the user's
root directory.patternstr - Pattern to search for.new_valuestr - 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:
# 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
@intercept_errors(message_prefix="Failed to search files: ")
async def search_files(path: str, pattern: str) -> SearchFilesResponseSearches for files and directories whose names match the
specified pattern. The pattern can be a simple string or a glob pattern.
Arguments:
pathstr - Path to the root directory to start search from. Relative paths are resolved based on the user's
root directory.patternstr - 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:
# 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
@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) -> NoneSets permissions and ownership for a file or directory. Any of the parameters can be None
to leave that attribute unchanged.
Arguments:
pathstr - Path to the file or directory. Relative paths are resolved based on the user's
root directory.modeOptional[str] - File mode/permissions in octal format
(e.g., "644" for rw-r--r--).ownerOptional[str] - User owner of the file.groupOptional[str] - Group owner of the file.
Example:
# 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
@overload
async def upload_file(file: bytes,
remote_path: str,
timeout: int = 30 * 60) -> NoneUploads 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:
filebytes - File contents as a bytes object.remote_pathstr - Path to the destination file. Relative paths are resolved based on the user's
root directory.timeoutint - Timeout for the upload operation in seconds. 0 means no timeout. Default is 30 minutes.
Example:
# 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
@overload
async def upload_file(local_path: str,
remote_path: str,
timeout: int = 30 * 60) -> NoneUploads 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_pathstr - Path to the local file to upload.remote_pathstr - Path to the destination file in the Sandbox. Relative paths are
resolved based on the user's root directory.timeoutint - Timeout for the upload operation in seconds. 0 means no timeout. Default is 30 minutes.
Example:
await sandbox.fs.upload_file("local_file.txt", "tmp/large_file.txt")AsyncFileSystem.upload\_files
@intercept_errors(message_prefix="Failed to upload files: ")
async def upload_files(files: List[FileUpload],
timeout: int = 30 * 60) -> NoneUploads multiple files to the Sandbox. If files already exist at the destination paths,
they will be overwritten.
Arguments:
filesList[FileUpload] - List of files to upload.timeoutint - Timeout for the upload operation in seconds. 0 means no timeout. Default is 30 minutes.
Example:
# 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
@dataclass
class FileUpload()Represents a file to be uploaded to the Sandbox.
Attributes:
sourceUnion[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.destinationstr - 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
class AsyncGit()Provides Git operations within a Sandbox.
Example:
# 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="[email protected]"
)AsyncGit.\_\_init\_\_
def __init__(sandbox_id: str, toolbox_api: ToolboxApi,
get_root_dir: Callable[[], Awaitable[str]])Initializes a new Git handler instance.
Arguments:
sandbox_idstr - The Sandbox ID.toolbox_apiToolboxApi - API client for Sandbox operations.get_root_dirCallable[[], str] - A function to get the default root directory of the Sandbox.
AsyncGit.add
@intercept_errors(message_prefix="Failed to add files: ")
async def add(path: str, files: List[str]) -> NoneStages the specified files for the next commit, similar to
running 'git add' on the command line.
Arguments:
pathstr - Path to the Git repository root. Relative paths are resolved based on the user's
root directory.filesList[str] - List of file paths or directories to stage, relative to the repository root.
Example:
# 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
@intercept_errors(message_prefix="Failed to list branches: ")
async def branches(path: str) -> ListBranchResponseLists branches in the repository.
Arguments:
pathstr - 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:
response = await sandbox.git.branches("workspace/repo")
print(f"Branches: {response.branches}")AsyncGit.clone
@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) -> NoneClones 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:
urlstr - Repository URL to clone from.pathstr - Path where the repository should be cloned. Relative paths are resolved based on the user's
root directory.branchOptional[str] - Specific branch to clone. If not specified,
clones the default branch.commit_idOptional[str] - Specific commit to clone. If specified,
the repository will be left in a detached HEAD state at this commit.usernameOptional[str] - Git username for authentication.passwordOptional[str] - Git password or token for authentication.
Example:
# 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
@intercept_errors(message_prefix="Failed to commit changes: ")
async def commit(path: str, message: str, author: str,
email: str) -> GitCommitResponseCreates a new commit with the staged changes. Make sure to stage
changes using the add() method before committing.
Arguments:
pathstr - Path to the Git repository root. Relative paths are resolved based on the user's
root directory.messagestr - Commit message describing the changes.authorstr - Name of the commit author.emailstr - Email address of the commit author.
Example:
# 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="[email protected]"
)AsyncGit.push
@intercept_errors(message_prefix="Failed to push changes: ")
async def push(path: str,
username: Optional[str] = None,
password: Optional[str] = None) -> NonePushes all local commits on the current branch to the remote
repository. If the remote repository requires authentication, provide
username and password/token.
Arguments:
pathstr - Path to the Git repository root. Relative paths are resolved based on the user's
root directory.usernameOptional[str] - Git username for authentication.passwordOptional[str] - Git password or token for authentication.
Example:
# 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
@intercept_errors(message_prefix="Failed to pull changes: ")
async def pull(path: str,
username: Optional[str] = None,
password: Optional[str] = None) -> NonePulls changes from the remote repository. If the remote repository requires authentication,
provide username and password/token.
Arguments:
pathstr - Path to the Git repository root. Relative paths are resolved based on the user's
root directory.usernameOptional[str] - Git username for authentication.passwordOptional[str] - Git password or token for authentication.
Example:
# 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
@intercept_errors(message_prefix="Failed to get status: ")
async def status(path: str) -> GitStatusGets the current Git repository status.
Arguments:
pathstr - 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:
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
class GitCommitResponse()Response from the git commit.
Attributes:
shastr - The SHA of the commit
File: src/content/docs/python-sdk/async/async-lsp-server.mdx
title: "AsyncLspServer" hideTitleOnPage: true
AsyncLspServer
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\_\_
def __init__(language_id: LspLanguageId, path_to_project: str,
toolbox_api: ToolboxApi, sandbox_id: str)Initializes a new LSP server instance.
Arguments:
language_idLspLanguageId - The language server type (e.g., LspLanguageId.TYPESCRIPT).path_to_projectstr - Absolute path to the project root directory.toolbox_apiToolboxApi - API client for Sandbox operations.instanceSandboxInstance - The Sandbox instance this server belongs to.
AsyncLspServer.start
@intercept_errors(message_prefix="Failed to start LSP server: ")
async def start() -> NoneStarts 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:
lsp = sandbox.create_lsp_server("typescript", "workspace/project")
await lsp.start() # Initialize the server
# Now ready for LSP operationsAsyncLspServer.stop
@intercept_errors(message_prefix="Failed to stop LSP server: ")
async def stop() -> NoneStops the language server.
This method should be called when the LSP server is no longer needed to
free up system resources.
Example:
# When done with LSP features
await lsp.stop() # Clean up resourcesAsyncLspServer.did\_open
@intercept_errors(message_prefix="Failed to open file: ")
async def did_open(path: str) -> NoneNotifies 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:
pathstr - Path to the opened file. Relative paths are resolved based on the project path
set in the LSP server constructor.
Example:
# When opening a file for editing
await lsp.did_open("workspace/project/src/index.ts")
# Now can get completions, symbols, etc. for this fileAsyncLspServer.did\_close
@intercept_errors(message_prefix="Failed to close file: ")
async def did_close(path: str) -> NoneNotify 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:
pathstr - Path to the closed file. Relative paths are resolved based on the project path
set in the LSP server constructor.
Example:
# When done editing a file
await lsp.did_close("workspace/project/src/index.ts")AsyncLspServer.document\_symbols
@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:
pathstr - 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:
# 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
@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:
querystr - Search query to match against symbol names.
Returns:
List[LspSymbol]- List of matching symbols from all files.
AsyncLspServer.sandbox\_symbols
@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:
querystr - 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:
# 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
@intercept_errors(message_prefix="Failed to get completions: ")
async def completions(path: str, position: Position) -> CompletionListGets completion suggestions at a position in a file.
Arguments:
pathstr - Path to the file. Relative paths are resolved based on the project path
set in the LSP server constructor.positionPosition - 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:
# 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
class LspLanguageId(Enum)Language IDs for Language Server Protocol (LSP).
Enum Members:
- PYTHON ("python")
- TYPESCRIPT ("typescript")
- JAVASCRIPT ("javascript")
Position
class Position()Represents a zero-based position in a text document,
specified by line number and character offset.
Attributes:
lineint - Zero-based line number in the document.characterint - Zero-based character offset on the line.
Position.\_\_init\_\_
def __init__(line: int, character: int)Initialize a new Position instance.
Arguments:
lineint - Zero-based line number in the document.characterint - Zero-based character offset on the line.
File: src/content/docs/python-sdk/async/async-object-storage.mdx
title: "AsyncObjectStorage" hideTitleOnPage: true
AsyncObjectStorage
class AsyncObjectStorage()AsyncObjectStorage class for interacting with object storage services.
Attributes:
endpoint_urlstr - The endpoint URL for the object storage service.aws_access_key_idstr - The access key ID for the object storage service.aws_secret_access_keystr - The secret access key for the object storage service.aws_session_tokenstr - The session token for the object storage service. Used for temporary credentials.bucket_namestr - The name of the bucket to use.
AsyncObjectStorage.upload
async def upload(path, organization_id, archive_base_path=None) -> strUploads a file to the object storage service.
Arguments:
pathstr - The path to the file to upload.organization_idstr - The organization ID to use.archive_base_pathstr - The base path to use for the archive.
File: src/content/docs/python-sdk/async/async-sandbox.mdx
title: "AsyncSandbox" hideTitleOnPage: true
AsyncSandbox
class AsyncSandbox(SandboxDto)Represents a Daytona Sandbox.
Attributes:
fsAsyncFileSystem - File system operations interface.gitAsyncGit - Git operations interface.processAsyncProcess - Process execution interface.idstr - Unique identifier for the Sandbox.organization_idstr - Organization ID of the Sandbox.snapshotstr - Daytona snapshot used to create the Sandbox.userstr - OS user running in the Sandbox.envDict[str, str] - Environment variables set in the Sandbox.labelsDict[str, str] - Custom labels attached to the Sandbox.publicbool - Whether the Sandbox is publicly accessible.targetstr - Target location of the runner where the Sandbox runs.cpuint - Number of CPUs allocated to the Sandbox.gpuint - Number of GPUs allocated to the Sandbox.memoryint - Amount of memory allocated to the Sandbox in GiB.diskint - Amount of disk space allocated to the Sandbox in GiB.stateSandboxState - Current state of the Sandbox (e.g., "started", "stopped").error_reasonstr - Error message if Sandbox is in error state.backup_stateSandboxBackupStateEnum - Current state of Sandbox backup.backup_created_atstr - When the backup was created.auto_stop_intervalint - Auto-stop interval in minutes.auto_archive_intervalint - Auto-archive interval in minutes.runner_domainstr - Domain name of the Sandbox runner.volumesList[str] - Volumes attached to the Sandbox.build_infostr - Build information for the Sandbox if it was created from dynamic build.created_atstr - When the Sandbox was created.updated_atstr - When the Sandbox was last updated.
AsyncSandbox.\_\_init\_\_
def __init__(sandbox_dto: SandboxDto, sandbox_api: SandboxApi,
toolbox_api: ToolboxApi, code_toolbox: SandboxCodeToolbox)Initialize a new Sandbox instance.
Arguments:
idstr - Unique identifier for the Sandbox.instanceSandboxInstance - The underlying Sandbox instance.sandbox_apiSandboxApi - API client for Sandbox operations.toolbox_apiToolboxApi - API client for toolbox operations.code_toolboxSandboxCodeToolbox - Language-specific toolbox implementation.
AsyncSandbox.refresh\_data
async def refresh_data() -> NoneRefreshes the Sandbox data from the API.
Example:
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
@intercept_errors(message_prefix="Failed to get sandbox root directory: ")
async def get_user_root_dir() -> strGets 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:
root_dir = await sandbox.get_user_root_dir()
print(f"Sandbox root: {root_dir}")AsyncSandbox.create\_lsp\_server
def create_lsp_server(language_id: LspLanguageId,
path_to_project: str) -> AsyncLspServerCreates a new Language Server Protocol (LSP) server instance.
The LSP server provides language-specific features like code completion,
diagnostics, and more.
Arguments:
language_idLspLanguageId - The language server type (e.g., LspLanguageId.PYTHON).path_to_projectstr - 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:
lsp = sandbox.create_lsp_server("python", "workspace/project")AsyncSandbox.set\_labels
@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:
labelsDict[str, str] - Dictionary of key-value pairs representing Sandbox labels.
Returns:
Dict[str, str]: Dictionary containing the updated Sandbox labels.
Example:
new_labels = sandbox.set_labels({
"project": "my-project",
"environment": "development",
"team": "backend"
})
print(f"Updated labels: {new_labels}")AsyncSandbox.start
@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:
timeoutOptional[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:
sandbox = daytona.get_current_sandbox("my-sandbox")
sandbox.start(timeout=40) # Wait up to 40 seconds
print("Sandbox started successfully")AsyncSandbox.stop
@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:
timeoutOptional[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:
sandbox = daytona.get_current_sandbox("my-sandbox")
sandbox.stop()
print("Sandbox stopped successfully")AsyncSandbox.delete
async def delete() -> NoneDeletes the Sandbox.
AsyncSandbox.wait\_for\_sandbox\_start
@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) -> NoneWaits 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:
timeoutOptional[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
@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) -> NoneWaits 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:
timeoutOptional[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
@intercept_errors(message_prefix="Failed to set auto-stop interval: ")
async def set_autostop_interval(interval: int) -> NoneSets 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:
intervalint - 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:
# Auto-stop after 1 hour
sandbox.set_autostop_interval(60)
# Or disable auto-stop
sandbox.set_autostop_interval(0)AsyncSandbox.set\_auto\_archive\_interval
@intercept_errors(message_prefix="Failed to set auto-archive interval: ")
async def set_auto_archive_interval(interval: int) -> NoneSets the auto-archive interval for the Sandbox.
The Sandbox will automatically archive after being continuously stopped for the specified interval.
Arguments:
intervalint - 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:
# Auto-archive after 1 hour
sandbox.set_autoarchive_interval(60)
# Or use the maximum interval
sandbox.set_autoarchive_interval(0)AsyncSandbox.get\_preview\_link
@intercept_errors(message_prefix="Failed to get preview link: ")
async def get_preview_link(port: int) -> PortPreviewUrlRetrieves 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:
portint - The port to open the preview link on.
Returns:
PortPreviewUrl- The response object for the preview link, which includes theurl
and thetoken(to access private sandboxes).
Example:
preview_link = sandbox.get_preview_link(3000)
print(f"Preview URL: {preview_link.url}")
print(f"Token: {preview_link.token}")AsyncSandbox.archive
@intercept_errors(message_prefix="Failed to archive sandbox: ")
async def archive() -> NoneArchives 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
@dataclass
class Resources()Resources configuration for Sandbox.
Attributes:
cpuOptional[int] - Number of CPU cores to allocate.memoryOptional[int] - Amount of memory in GiB to allocate.diskOptional[int] - Amount of disk space in GiB to allocate.gpuOptional[int] - Number of GPUs to allocate.
Example:
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
)