# Interpreter (/docs/go-sdk/interpreter)

> For AI agents: the complete documentation index is at https://www.daytona.com/llms.txt.

## Interpreter [#interpreter]

```go
type Interpreter struct {
	// contains filtered or unexported fields
}
```

Interpreter runs code in stateful language kernels. Obtain it from
Sandbox.Interpreter. Its handles and execution queues are concurrency-safe.

#### Interpreter.ConnectContext [#interpreterconnectcontext]

```go
func (s *Interpreter) ConnectContext(id, language string) (*InterpreterContext, error)
```

ConnectContext binds an existing context ID and language without a request.
Empty languages and invalid path IDs return ErrBadRequest.

#### Interpreter.ConnectContextJSON [#interpreterconnectcontextjson]

```go
func (s *Interpreter) ConnectContextJSON(identity InterpreterContextJSON) (*InterpreterContext, error)
```

ConnectContextJSON reconnects a serialized identity without a request.
Identities belonging to another sandbox return ErrBadRequest.

#### Interpreter.CreateContext [#interpretercreatecontext]

```go
func (s *Interpreter) CreateContext(
	ctx context.Context, language string, opts *CreateInterpreterContextOptions,
) (*InterpreterContext, error)
```

CreateContext creates independent kernel state. Language is case-sensitive
and server-defined; unsupported languages return ErrUnsupportedOperation.
If a named context's response cannot be parsed or bound, the error identifies
the context that may exist and preserves the failure as its cause.

**Example**:

```go
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
client, err := daytona.New()
if err != nil {
	log.Print(err)
	return
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Print(err)
	return
}
kernel, err := sandbox.Interpreter().CreateContext(ctx, "python", nil)
if err != nil {
	log.Print(err)
	return
}
defer func() {
	if closeErr := kernel.Close(ctx); closeErr != nil {
		log.Print(closeErr)
	}
}()
if _, err = kernel.Run(ctx, "x = 21", nil); err != nil {
	log.Print(err)
	return
}
result, err := kernel.Run(ctx, "print(x * 2)", nil)
if err != nil {
	log.Print(err)
	return
}
fmt.Print(result.Logs.Stdout)
```

#### Interpreter.DeleteContext [#interpreterdeletecontext]

```go
func (s *Interpreter) DeleteContext(ctx context.Context, id string) error
```

DeleteContext deletes kernel state by ID. ErrSessionNotFound is returned
unchanged; a failed deletion preserves execution serialization.

#### Interpreter.ListContexts [#interpreterlistcontexts]

```go
func (s *Interpreter) ListContexts(ctx context.Context) ([]*InterpreterContext, error)
```

ListContexts returns all interpreter contexts in one request. Shell sessions
are excluded; unknown kernel languages are preserved.

#### Interpreter.Run [#interpreterrun]

```go
func (s *Interpreter) Run(ctx context.Context, code string, opts *RunCodeOptions) (*RunCodeResult, error)
```

Run executes code and returns stdout, stderr, rich outputs and kernel errors.
Timeout includes time queued behind another run in the same context. An
expired queued run returns ProcessReasonTimedOut with an empty ProcessID.
Callbacks must not synchronously run more code in the same context.

## InterpreterContext [#interpretercontext]

```go
type InterpreterContext struct {
	// contains filtered or unexported fields
}
```

InterpreterContext is an independent kernel's concurrency-safe handle.
Obtain it from CreateContext, ConnectContext, ConnectContextJSON or ListContexts.

#### InterpreterContext.Close [#interpretercontextclose]

```go
func (c *InterpreterContext) Close(ctx context.Context) error
```

Close deletes the context and its kernel state. ErrSessionNotFound is returned
unchanged when the context has already disappeared.

#### InterpreterContext.ID [#interpretercontextid]

```go
func (c *InterpreterContext) ID() string
```

ID returns the context's stable ID.

#### InterpreterContext.Identity [#interpretercontextidentity]

```go
func (c *InterpreterContext) Identity() InterpreterContextJSON
```

Identity returns a credential-free identity suitable for ConnectContextJSON.

#### InterpreterContext.Language [#interpretercontextlanguage]

```go
func (c *InterpreterContext) Language() string
```

Language returns the context's language, an open server-defined vocabulary.

#### InterpreterContext.MarshalJSON [#interpretercontextmarshaljson]

```go
func (c InterpreterContext) MarshalJSON() ([]byte, error)
```

MarshalJSON serializes only the context's identity, without credentials.

#### InterpreterContext.Run [#interpretercontextrun]

```go
func (c *InterpreterContext) Run(
	ctx context.Context, code string, opts *InterpreterContextRunOptions,
) (*RunCodeResult, error)
```

Run executes code in this context. A lost context returns ErrSessionNotFound;
the SDK never recreates it or reruns the code automatically.

#### InterpreterContext.SandboxID [#interpretercontextsandboxid]

```go
func (c *InterpreterContext) SandboxID() string
```

SandboxID returns the sandbox containing the context.

## CreateInterpreterContextOptions [#createinterpretercontextoptions]

```go
type CreateInterpreterContextOptions struct {
	// ContextID optionally requests a specific ID; empty lets the server choose.
	ContextID string
	// Cwd sets the default working directory.
	Cwd string
	// Env sets the environment for every execution in the context.
	// Nil omits it; an empty map sends an explicit empty environment override.
	Env map[string]string
}
```

CreateInterpreterContextOptions configures an independent kernel context.

## InterpreterContextJSON [#interpretercontextjson]

```go
type InterpreterContextJSON struct {
	// SandboxID identifies the sandbox owning the context.
	SandboxID string `json:"sandboxId"`
	// ContextID identifies the kernel context.
	ContextID string `json:"contextId"`
	// Language identifies the context's language.
	Language string `json:"language"`
}
```

InterpreterContextJSON is the cross-SDK, credential-free context identity.

## InterpreterContextRunOptions [#interpretercontextrunoptions]

```go
type InterpreterContextRunOptions struct {
	// Cwd overrides the context's working directory for this execution.
	Cwd string
	// Timeout bounds queueing, submission and execution. Zero waits indefinitely
	// but keeps the client's request timeout for submission. WaitForever and
	// NoTimeout also remove the submission timeout. Expiry interrupts the kernel.
	Timeout time.Duration
	// Stdout receives stdout as it arrives. Nil buffers output only.
	Stdout io.Writer
	// Stderr receives stderr as it arrives. Nil buffers output only.
	Stderr io.Writer
	// OnOutput receives rich display and execution results in log order.
	OnOutput func(InterpreterOutput) error
	// OnError receives interpreter errors in log order.
	OnError func(InterpreterError) error
	// OnLog receives every log frame, including setup and unknown channels.
	// Callback errors stop delivery and are wrapped as SDK errors.
	OnLog func(LogFrame) error
}
```

InterpreterContextRunOptions configures execution in an existing context.
Writer and callback failures return a partial result with Process.ProcessID
and preserve the local error, with the same best-effort detached interrupt
semantics as RunCodeOptions.

## InterpreterError [#interpretererror]

```go
type InterpreterError struct {
	// Name is the exception class name.
	Name string
	// Value is the exception message.
	Value string
	// Traceback contains the kernel's formatted stack trace.
	Traceback []string
}
```

InterpreterError describes an exception reported by the language kernel.
It is part of a successful RunCodeResult, not a transport error.

## InterpreterLogs [#interpreterlogs]

```go
type InterpreterLogs struct {
	// Stdout concatenates stdout frames in order.
	Stdout string
	// Stderr concatenates stderr frames in order.
	Stderr string
}
```

InterpreterLogs contains only stdout and stderr, excluding setup narration.

## InterpreterOutput [#interpreteroutput]

```go
type InterpreterOutput struct {
	// Data preserves every MIME value as encoded JSON.
	Data map[string]JSONValue
	// IsMainResult is true only for execute_result frames.
	IsMainResult bool
	// Text is text/plain, when the value is a string.
	Text *string
	// HTML is text/html, when the value is a string.
	HTML *string
	// PNG is image/png, usually a base64-encoded string.
	PNG *string
	// SVG is image/svg+xml, when the value is a string.
	SVG *string
	// JSON is application/json as encoded JSON; nil means absent.
	JSON JSONValue
}
```

InterpreterOutput is a rich MIME bundle emitted by a language kernel.

## InterpreterProcess [#interpreterprocess]

```go
type InterpreterProcess struct {
	WaitResult
	// ProcessID is empty when the caller budget expired before submission.
	ProcessID string
}
```

InterpreterProcess records the server's execution outcome.

## RunCodeOptions [#runcodeoptions]

```go
type RunCodeOptions struct {
	// Language selects the kernel language; empty defaults to python or Context's language.
	Language string
	// Context selects an existing context. It cannot be combined with ContextID or Isolated.
	Context *InterpreterContext
	// ContextID selects an existing context by ID and requires Language.
	ContextID string
	// Isolated creates a throwaway context and deletes it best-effort after execution.
	Isolated bool
	// Cwd overrides the execution's working directory.
	Cwd string
	// Env sets environment variables for implicit or isolated runs. Nil omits env;
	// an empty non-nil map sends {}. An explicit context takes its environment
	// at creation and rejects even an empty Env map.
	Env map[string]string
	// Timeout bounds queueing, setup and execution; expiry interrupts the kernel.
	// Zero waits indefinitely while keeping the client's setup request timeout.
	// WaitForever, NoTimeout and durations above the timer maximum remove both bounds.
	Timeout time.Duration
	// Stdout receives stdout frames as they arrive, while still retaining Logs.
	Stdout io.Writer
	// Stderr receives stderr frames as they arrive, while still retaining Logs.
	Stderr io.Writer
	// OnOutput receives rich outputs serially; an error ends delivery.
	OnOutput func(InterpreterOutput) error
	// OnError receives kernel exceptions serially; an error ends delivery.
	OnError func(InterpreterError) error
	// OnLog receives every frame serially, including setup and unknown channels.
	// Failures use the partial-result and cleanup semantics described on RunCodeOptions.
	OnLog func(LogFrame) error
}
```

RunCodeOptions configures code execution. Nil selects the shared Python kernel.
A writer or callback error stops delivery and attempts to interrupt the cell
with a detached five-second budget, as on Timeout. Run returns a partial result
with Process.ProcessID and unknown Reason alongside an SDK error preserving the
local cause through errors.Is. Cleanup is best-effort: its failure does not
replace the local error, and a successful interrupt does not confirm cell exit.
Writers and callbacks run synchronously and must not block indefinitely.
Any failure after process creation returns the partial result with
Process.ProcessID and unknown Reason alongside the error, including without
writers or callbacks. Other failures do not retry the stream or trigger
additional interruption; Timeout retains its documented interrupt semantics.
Reconnect that process to wait, resume its logs, or interrupt it explicitly.

## RunCodeResult [#runcoderesult]

```go
type RunCodeResult struct {
	// Process contains the process identity and unmodified wait outcome.
	Process InterpreterProcess
	// Results contains rich display and expression outputs in log order.
	Results []InterpreterOutput
	// Logs contains channel-filtered stdout and stderr.
	Logs InterpreterLogs
	// Error is the last kernel exception, or nil when none was reported.
	Error *InterpreterError
}
```

RunCodeResult contains a code execution's outcome and decomposed outputs.
Reconnected process handles support replay/control, not reconstruction of this result.
