Sign Up

Code Execution

Run Python, TypeScript, and JavaScript code in your sandboxes through language kernels.

Daytona runs Python, TypeScript, and JavaScript code in sandboxes through language kernels, so untrusted or generated code executes in isolation from your application.

Every run is a code process that executes in a session with a language kernel. The kernel keeps state between runs in the same session, so variables, imports, and functions defined in one run are available in the next. Runs use a shared kernel per language by default; isolated runs and interpreter contexts give code its own kernel. To run shell commands and manage long-running processes, see process execution. To follow a run's output live, see log streaming.

Use cases

Code execution is used when an application runs Python, TypeScript, or JavaScript that it did not write or does not trust.

  • AI-generated code. An agent writes code, runs it in the sandbox, and reads the output and errors to correct its next attempt. The code runs isolated from your application. Each result also holds the exit status of the process.

  • Data analysis. The kernel keeps data, imports, and functions in memory between runs, so each step builds on the previous one, as in a notebook. Runs without a context share one kernel per language, so later runs in that language see the same data. The first run in a language installs the kernel, so that run can take longer than later ones.

  • Charts and tables. Runs that plot or display data return charts and tables as artifacts with the result. Each artifact is keyed by MIME type, so an application renders it in the right format. A flag on each result tells the value of the last expression apart from displayed outputs.

  • Code interpreters for users. Each user or conversation gets its own interpreter context, so state from one does not reach another. A context has its own kernel, working directory, and environment. Its kernel uses memory even while idle, until the application deletes the context.

  • One-off runs. An isolated kernel runs code with no state from earlier runs. The session is deleted after the run, so nothing the code defines reaches other runs. An isolated run cannot be combined with an interpreter context.

Run code

Run code in a sandbox. Runs without a context share one kernel per language, so state from one run is available to later runs in that language. The default language is Python.

The result contains the standard output and standard error, rich outputs, the exception if the code raised one, and the exit status of the process.

from daytona import Daytona

daytona = Daytona()
sandbox = daytona.v2.create()

response = sandbox.run_code('''
def greet(name):
    return f"Hello, {name}!"

print(greet("Daytona"))
''')
print(response.logs.stdout)
ParameterTypeDescription
codestrSets the code to run. This parameter is required.
languagestrSets the language: python, typescript, or javascript. The default is python.
contextInterpreterContextRuns the code in an interpreter context instead of the shared kernel.
isolatedboolRuns the code in a temporary kernel. The default is False.
cwdstrSets the working directory of the shared kernel. Only the run that starts the kernel sets it, and later runs ignore it. To run code in another directory, use an interpreter context or an isolated run.
envMapping[str, str]Sets environment variables for the shared kernel. Only the run that starts the kernel sets them. A later run that passes different variables raises an error with code UNSUPPORTED_OPERATION.
timeoutfloatSets how many seconds the client waits. On timeout, the kernel is interrupted and the result of the run is returned with exit code 1; a run still queued behind another run on the same kernel returns reason timed_out without an exit code. The kernel keeps its state. 0 means no limit. The default is no limit.

The response has the following fields:

FieldDescription
logsHolds the standard output and standard error.
resultsHolds the rich outputs.
errorHolds the exception, if the code raised one.
processHolds the exit status of the process: 0 when the code finished, and 1 when it raised an exception or was interrupted. If the kernel stopped during the run, the reason is lost and the next run starts a new kernel without the earlier state.

Artifacts

Rich outputs such as charts and tables are returned with the result, keyed by MIME type.

from daytona import Daytona

daytona = Daytona()
sandbox = daytona.v2.create()
sandbox.process.run("pip install matplotlib numpy")

code = '''
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 30)
plt.plot(x, np.sin(x))
plt.title("Sine wave")
plt.show()
'''

response = sandbox.run_code(code)
if response.error:
    print(response.error.name, response.error.value)
for result in response.results:
    print(list(result.data))  # MIME types, for example ['image/png', 'text/plain']

The response has the following fields:

FieldDescription
resultsHolds the rich outputs.
text, html, png, svg, jsonEach of these fields of a result mirrors the matching MIME type in data.
is_main_resultIs True for the value of the last expression and False for displayed outputs.

Run code in an isolated kernel

Run code in a temporary kernel that starts with no state. Daytona creates a session with a new kernel, runs the code, and deletes the session after the run. Nothing the code defines is visible to other runs, and the code does not see state from the shared kernel or from interpreter contexts.

from daytona import Daytona

daytona = Daytona()
sandbox = daytona.v2.create()

sandbox.run_code("value = 42")

# The isolated kernel does not see variables from the shared kernel
response = sandbox.run_code("print(value)", isolated=True)
if response.error:
    print(response.error.name)  # NameError
ParameterTypeDescription
isolatedboolRuns the code in a temporary kernel when set to True. Each run starts a new kernel, so timeout must also cover the kernel start. If timeout runs out before the kernel starts, the call raises an error with code REQUEST_TIMEOUT. The default is False. This parameter cannot be combined with context.
cwdstrSets the working directory of the temporary kernel.
envMapping[str, str]Sets environment variables of the temporary kernel.

Interpreter contexts

An interpreter context is a session with its own language kernel, working directory, and environment. State persists across runs in a context and is not shared with the shared kernel or other contexts. A context lives until deleted, so its kernel uses memory while idle.

In the Toolbox API, a context is a session that runs a language kernel. Shell sessions are not created through this endpoint; see sessions.

Create a context

Create an interpreter context and run code in it. Run code with the context handle, or pass the handle to a run in the sandbox.

from daytona import Daytona

daytona = Daytona()
sandbox = daytona.v2.create()

ctx = sandbox.interpreter.create_context(language="python", env={"STAGE": "dev"})
try:
    ctx.run("value = 'stored in ctx'")
    result = sandbox.run_code("print(value)", context=ctx)
    print(result.logs.stdout)
finally:
    ctx.close()
ParameterTypeDescription
languagestrSets the language: python, typescript, or javascript. This parameter is required.
context_idstrSets the context ID for reconnecting later. The ID has at most 128 ASCII letters, digits, ., _, and -, and is unique in the sandbox. An ID that is in use returns NAME_CONFLICT. If omitted, an ID is generated.
cwdstrSets the working directory of the kernel.
envMapping[str, str]Sets the kernel environment variables. Runs in a context do not accept env.

List contexts

List a sandbox's interpreter contexts. The list also includes the shared kernel of each language that has run code, with the ID code-python, code-typescript, or code-javascript. The list does not include shell sessions.

from daytona import Daytona

daytona = Daytona()
sandbox = daytona.v2.create()

for ctx in sandbox.interpreter.list_contexts():
    print(f"Context: {ctx.context_id}, Language: {ctx.language}")

Reconnect to a context

Reconnect to an existing context from another worker or process. Contexts are addressed by ID, so any client with the sandbox ID and the context ID can run code in the context.

from daytona import Daytona

daytona = Daytona()
sandbox = daytona.v2.create()

# Worker A: create a context with a known ID
ctx = sandbox.interpreter.create_context(language="python", context_id="my-context")
ctx.run("x = 42")

# Worker B: reconnect to the context by ID
context = sandbox.interpreter.connect_context("my-context", language="python")
response = context.run("print(x)")
print(response.logs.stdout)  # 42

# Or persist the context in worker A and reconnect from the saved dict, which carries the language
saved = ctx.to_json()  # {"sandboxId": "...", "contextId": "my-context", "language": "python"}
context = sandbox.interpreter.connect_context(saved)
ParameterTypeDescription
languagestrSets the context language. This parameter is required when you pass an ID. Without language, connect_context() raises DaytonaError with code BAD_REQUEST.

Delete a context

Delete an interpreter context. Deleting a context shuts its kernel down and frees its memory.

from daytona import Daytona

daytona = Daytona()
sandbox = daytona.v2.create()

ctx = sandbox.interpreter.create_context(language="python")
try:
    ctx.run("data = list(range(10_000_000))")
finally:
    sandbox.interpreter.delete_context(ctx)

Errors

The SDKs raise these errors with the codes in the following table, and the Toolbox API returns them in the code field. An exception in the code itself is not an error of the request: it is returned in the result.

CodeMeaningWhat to do
SESSION_NOT_FOUNDThe context does not exist, or it was deleted.Create the context again. Its earlier state is lost.
NAME_CONFLICTA context with this ID already exists in the sandbox.Use another ID, or reconnect to the existing context.
UNSUPPORTED_OPERATIONA run passed environment variables that its kernel does not take: a run on the shared kernel with variables other than those it started with, or an API run with sessionId and env.Set the variables when you create an interpreter context.
BAD_REQUESTA context ID without a language, a language that does not match the context, an isolated run with a context, or an SDK run in a context that passes environment variables.Pass the language of the context, run without isolated, or set the variables when you create the context.
REQUEST_TIMEOUTThe timeout of an isolated run ran out before its kernel started.Raise the timeout.

Permissions

Code execution runs through the toolbox of a sandbox. Access is governed by one project permission, which you can grant to an organization role or an API key.

A sandbox access token with the toolbox:exec operation grants the same access to a single sandbox, without an API key. The sandbox read permission alone does not grant toolbox access.

PermissionGrants
write:sandboxesRun code and manage interpreter contexts