# Process (/docs/go-sdk/process)

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

## PTY [#pty]

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

PTY manages interactive terminals in one sandbox.
Obtain it from Sandbox.PTY.

#### PTY.Connect [#ptyconnect]

```go
func (s *PTY) Connect(ctx context.Context, id string) (*PTYConnection, error)
```

Connect attaches to an existing terminal by process ID or live alias.
The context bounds the returned connection's lifetime.

#### PTY.Create [#ptycreate]

```go
func (s *PTY) Create(ctx context.Context, command string, opts *PTYOptions) (*PTYConnection, error)
```

Create starts a terminal and attaches to it. The context bounds the returned
connection's lifetime. If an accepted create record is malformed or attaching fails, Create attempts to delete the
process with a separate, at-most-five-second cleanup budget and returns the
original error.

**Example**:

```go
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Cancelling ctx closes the terminal connection.
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
connection, err := sandbox.PTY().Create(ctx, "", &daytona.PTYOptions{
	Terminal: &daytona.TerminalSize{Cols: 100, Rows: 30},
})
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := connection.Close(); closeErr != nil {
		log.Print(closeErr)
	}
	if deleteErr := sandbox.PTY().Delete(ctx, connection.Handle().ID()); deleteErr != nil {
		log.Print(deleteErr)
	}
}()
if _, err = connection.Write([]byte("printf 'hello\\n'\n")); err != nil {
	log.Fatal(err)
}
buffer := make([]byte, 4096)
n, err := connection.Read(buffer)
if err != nil {
	log.Fatal(err)
}
fmt.Print(string(buffer[:n]))
```

#### PTY.Delete [#ptydelete]

```go
func (s *PTY) Delete(ctx context.Context, id string) error
```

Delete stops a terminal and deletes its record and logs. It checks the
server's process kind first and returns ErrUnsupportedOperation for every
non-PTY kind, including unknown future kinds, without sending a signal.

#### PTY.List [#ptylist]

```go
func (s *PTY) List(ctx context.Context) (*Page[ProcessInfo], error)
```

List returns one envelope containing the sandbox's terminal processes.

#### PTY.Start [#ptystart]

```go
func (s *PTY) Start(ctx context.Context, command string, opts *PTYOptions) (*ProcessHandle, error)
```

Start starts a detached terminal. An empty command selects the sandbox's
default shell. Defaults are 80 columns, 24 rows, TERM=xterm-256color, open
stdin and logs retained until cleanup. Invalid options return ErrBadRequest.
A malformed create response with a valid ID returns a reconnectable handle alongside the error.

## PTYConnection [#ptyconnection]

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

PTYConnection is a terminal's live byte stream, safe for concurrent use.
It implements io.ReadWriteCloser. Read, Write and Close intentionally take no
context to satisfy those interfaces: the context passed to Attach, Connect
or Create controls their lifetime, and Client.Close cancels them too.
Keep reading to process terminal output and connection control frames.
Close releases the connection without killing or deleting the process.

#### PTYConnection.Close [#ptyconnectionclose]

```go
func (c *PTYConnection) Close() error
```

Close immediately disconnects and unblocks pending I/O without waiting for a
remote close handshake. It is idempotent and does not stop the process.

#### PTYConnection.Handle [#ptyconnectionhandle]

```go
func (c *PTYConnection) Handle() *ProcessHandle
```

Handle returns the process handle for metadata, signals and deletion.

#### PTYConnection.Read [#ptyconnectionread]

```go
func (c *PTYConnection) Read(data []byte) (int, error)
```

Read reads terminal bytes across binary and text message boundaries.
A normal remote close returns io.EOF; abnormal closure is an SDK error.

#### PTYConnection.Resize [#ptyconnectionresize]

```go
func (c *PTYConnection) Resize(ctx context.Context, size TerminalSize) error
```

Resize changes the terminal's dimensions using the supplied request context.

#### PTYConnection.Write [#ptyconnectionwrite]

```go
func (c *PTYConnection) Write(data []byte) (int, error)
```

Write sends exact bytes to the terminal, bounded by the attach context.

## ProcessHandle [#processhandle]

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

ProcessHandle controls one process and is safe for concurrent use. Code handles
reconnected from an identity support replay, wait and kill, but do not rebuild
rich interpreter results; use Interpreter.Run for those.

#### ProcessHandle.Attach [#processhandleattach]

```go
func (h *ProcessHandle) Attach(ctx context.Context) (*PTYConnection, error)
```

Attach connects to this process's terminal. Known non-PTY kinds return
ErrUnsupportedOperation; an ID-only handle lets the server decide.
The request timeout bounds opening only, while ctx and Client.Close bound
the connection's entire lifetime. The caller must close the connection.

**Example**:

```go
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
handle, err := sandbox.Process().Connect("terminal-process-id")
if err != nil {
	log.Fatal(err)
}
connection, err := handle.Attach(ctx)
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := connection.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
if err = connection.Resize(ctx, daytona.TerminalSize{Cols: 120, Rows: 40}); err != nil {
	log.Fatal(err)
}
fmt.Println(connection.Handle().ID())
```

#### ProcessHandle.CloseStdin [#processhandleclosestdin]

```go
func (h *ProcessHandle) CloseStdin(ctx context.Context) error
```

CloseStdin sends EOF. It is separate from deleting or disconnecting the process.

#### ProcessHandle.Delete [#processhandledelete]

```go
func (h *ProcessHandle) Delete(ctx context.Context) error
```

Delete removes the process and its logs, stopping it if needed. It does not
hide ErrProcessNotFound or ErrUnsupportedOperation.

#### ProcessHandle.Get [#processhandleget]

```go
func (h *ProcessHandle) Get(ctx context.Context) (*ProcessInfo, error)
```

Get fetches current metadata, including the live cwd of a shell session.

#### ProcessHandle.ID [#processhandleid]

```go
func (h *ProcessHandle) ID() string
```

ID returns the stable process ID or alias used to connect.

#### ProcessHandle.Kill [#processhandlekill]

```go
func (h *ProcessHandle) Kill(ctx context.Context, opts *KillProcessOptions) error
```

Kill sends a signal (TERM by default), with optional escalation. INT interrupts
code cells and session commands; a terminal process returns ErrProcessTerminal.

#### ProcessHandle.Kind [#processhandlekind]

```go
func (h *ProcessHandle) Kind() ProcessKind
```

Kind returns the creation kind, or ProcessKindUnknown for an ID-only connection.

#### ProcessHandle.LogPage [#processhandlelogpage]

```go
func (h *ProcessHandle) LogPage(ctx context.Context, opts *ProcessLogsOptions) (*ProcessLogPage, error)
```

LogPage reads one retained log page. ErrCursorExpired includes the server's
first available cursor. The result owns its frames.

#### ProcessHandle.Logs [#processhandlelogs]

```go
func (h *ProcessHandle) Logs(ctx context.Context, opts *ProcessLogsOptions) iter.Seq2[LogFrame, error]
```

Logs follows replayed and live log frames until EOF. For terminal-state and
retention-warning events use StreamLogs. Breaking iteration closes only this stream.

#### ProcessHandle.Resize [#processhandleresize]

```go
func (h *ProcessHandle) Resize(ctx context.Context, size TerminalSize) error
```

Resize changes a PTY's size. Other known kinds return ErrUnsupportedOperation.

#### ProcessHandle.SandboxID [#processhandlesandboxid]

```go
func (h *ProcessHandle) SandboxID() string
```

SandboxID returns the owning sandbox ID.

#### ProcessHandle.StreamLogs [#processhandlestreamlogs]

```go
func (h *ProcessHandle) StreamLogs(ctx context.Context, opts *ProcessLogsOptions) iter.Seq2[ProcessLogEvent, error]
```

StreamLogs follows the log through an explicit EOF event. Missing EOF is
ErrConnection, never a silently complete log. Every event is bounded by the
client's max response size. Resume with the last event's cursor after failure.
Breaking iteration closes the response; ctx and Client.Close cancel blocked reads.

#### ProcessHandle.ToJSON [#processhandletojson]

```go
func (h *ProcessHandle) ToJSON() ProcessHandleJSON
```

ToJSON returns an identity that ConnectIdentity accepts on another worker.

#### ProcessHandle.Wait [#processhandlewait]

```go
func (h *ProcessHandle) Wait(ctx context.Context, opts *WaitProcessOptions) (*WaitResult, error)
```

Wait observes completion. Nil options wait indefinitely; a positive Timeout
returns reason timed_out without stopping execution. Cancellation and transport
errors return err. Non-zero exit codes are successful observations, not errors.

#### ProcessHandle.Write [#processhandlewrite]

```go
func (h *ProcessHandle) Write(ctx context.Context, data []byte) (int, error)
```

Write sends exact bytes to stdin using base64, returning the accepted byte count.
The process must have been started with Stdin open. Errors include
ErrStdinClosed, ErrStdinUnavailable and ErrProcessTerminal.

## Processes [#processes]

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

Processes manages commands and persistent shells in one sandbox.

#### Processes.Connect [#processesconnect]

```go
func (s *Processes) Connect(id string) (*ProcessHandle, error)
```

Connect binds a process ID or live alias without a request.

#### Processes.ConnectIdentity [#processesconnectidentity]

```go
func (s *Processes) ConnectIdentity(identity ProcessHandleJSON) (*ProcessHandle, error)
```

ConnectIdentity reconnects a serialized handle, refusing cross-sandbox identities.

#### Processes.ConnectSession [#processesconnectsession]

```go
func (s *Processes) ConnectSession(id string) (*Session, error)
```

ConnectSession binds a shell session ID without a request.

#### Processes.ConnectSessionIdentity [#processesconnectsessionidentity]

```go
func (s *Processes) ConnectSessionIdentity(identity SessionJSON) (*Session, error)
```

ConnectSessionIdentity reconnects a serialized shell, rejecting another sandbox.

#### Processes.CreateSession [#processescreatesession]

```go
func (s *Processes) CreateSession(ctx context.Context, opts *CreateSessionOptions) (*Session, error)
```

CreateSession creates a persistent shell. Non-POSIX shells are refused by the server.
A malformed create response with a valid ID returns a reconnectable session alongside the error.

**Example**:

```go
ctx := context.Background()
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sb, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
session, err := sb.Process().CreateSession(ctx, &daytona.CreateSessionOptions{Cwd: "/tmp"})
if err != nil {
	log.Fatal(err)
}
defer func() {
	if deleteErr := session.Delete(ctx); deleteErr != nil {
		log.Print(deleteErr)
	}
}()
if _, err = session.Run(ctx, "export ANSWER=42", nil); err != nil {
	log.Fatal(err)
}
result, err := session.Run(ctx, `printf '%s' "$ANSWER"`, nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println(result.Stdout)
```

#### Processes.Delete [#processesdelete]

```go
func (s *Processes) Delete(ctx context.Context, id string) error
```

Delete stops a process and removes its record and logs. A running code cell
may return ErrUnsupportedOperation; interrupt it first.

#### Processes.Get [#processesget]

```go
func (s *Processes) Get(ctx context.Context, id string) (*ProcessInfo, error)
```

Get fetches metadata by process ID or live alias. Missing processes return ErrProcessNotFound.

#### Processes.KillAll [#processeskillall]

```go
func (s *Processes) KillAll(ctx context.Context, tag string, opts *KillAllProcessesOptions) ([]string, error)
```

KillAll stops tagged processes and their descendants, retaining logs and records.
It returns stopped IDs. ErrProcessKillIncomplete is safe to retry;
ErrUnsupportedOperation indicates unavailable process containment (including macOS).

#### Processes.List [#processeslist]

```go
func (s *Processes) List(ctx context.Context, opts *ListProcessesOptions) (*Page[ProcessInfo], error)
```

List returns one envelope of processes. The server does not paginate this list.

#### Processes.ListAll [#processeslistall]

```go
func (s *Processes) ListAll(ctx context.Context, opts *ListProcessesOptions) iter.Seq2[ProcessInfo, error]
```

ListAll iterates List lazily. Breaking iteration performs no additional requests.

#### Processes.Run [#processesrun]

```go
func (s *Processes) Run(ctx context.Context, command string, opts *ExecOptions) (*ProcessResult, error)
```

Run is the process namespace form of Sandbox.Exec.

#### Processes.RunArgs [#processesrunargs]

```go
func (s *Processes) RunArgs(ctx context.Context, argv []string, opts *ExecOptions) (*ProcessResult, error)
```

RunArgs is the process namespace form of Sandbox.ExecArgs.

#### Processes.Start [#processesstart]

```go
func (s *Processes) Start(ctx context.Context, command string, opts *ProcessStartOptions) (*ProcessHandle, error)
```

Start launches a background shell command and returns immediately. Use
StartArgs for untrusted arguments; use CreateSession to retain shell state.
ExecutionTimeout stops the process tree; context cancellation only stops the request.
A malformed create response with a valid ID returns a reconnectable handle alongside the error.

**Example**:

```go
ctx := context.Background()
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sb, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
handle, err := sb.Process().Start(ctx, "python3 -m http.server 8080", &daytona.ProcessStartOptions{Tag: "web"})
if err != nil {
	log.Fatal(err)
}
fmt.Println(handle.ID()) // Store handle.ToJSON() to reconnect on another worker.
if err = handle.Kill(ctx, nil); err != nil {
	log.Print(err)
}
```

#### Processes.StartArgs [#processesstartargs]

```go
func (s *Processes) StartArgs(
	ctx context.Context, argv []string, opts *ProcessStartOptions,
) (*ProcessHandle, error)
```

StartArgs launches argv without a shell. argv must contain a non-empty executable.

## Session [#session]

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

Session is a persistent POSIX shell. Commands execute in order and retain cwd,
exported variables and functions. INT interrupts one command without ending the
shell. Sessions survive pause/resume, not a sandbox stop/start.

#### Session.Delete [#sessiondelete]

```go
func (s *Session) Delete(ctx context.Context) error
```

Delete ends the shell and deletes it and all of its command records.

#### Session.Get [#sessionget]

```go
func (s *Session) Get(ctx context.Context) (*ProcessInfo, error)
```

Get reads live shell metadata, including its current working directory.

#### Session.ID [#sessionid]

```go
func (s *Session) ID() string
```

ID returns the shell's process ID.

#### Session.Run [#sessionrun]

```go
func (s *Session) Run(ctx context.Context, command string, opts *SessionRunOptions) (*ProcessResult, error)
```

Run executes in the persistent shell and collects output. Non-zero ExitCode
is not an error. Shell configuration belongs on CreateSession, not this call.
Any failure after creation preserves ProcessID and collected output with unknown Reason.

#### Session.SandboxID [#sessionsandboxid]

```go
func (s *Session) SandboxID() string
```

SandboxID returns the owning sandbox.

#### Session.Start [#sessionstart]

```go
func (s *Session) Start(ctx context.Context, command string, opts *SessionStartOptions) (*ProcessHandle, error)
```

Start queues a command in this shell and returns its handle immediately.
ErrSessionNotFound and ErrSessionEnded surface unchanged; no shell is recreated.
A malformed create response with a valid ID returns a reconnectable handle alongside the error.

#### Session.ToJSON [#sessiontojson]

```go
func (s *Session) ToJSON() SessionJSON
```

ToJSON returns a credential-free identity accepted by ConnectSessionIdentity.

## CreateSessionOptions [#createsessionoptions]

```go
type CreateSessionOptions struct {
	// Tag is inherited by the shell's commands; uses the process tag rules.
	Tag string
	// Cwd sets the initial directory.
	Cwd string
	// Env adds environment variables to the shell. Nil omits env;
	// an empty non-nil map sends {}.
	Env map[string]string
	// Shell selects a POSIX shell (bash/sh/dash/zsh/ksh).
	Shell string
	// Login selects a login shell; nil uses the sandbox default.
	Login *bool
	// Name is an optional live alias.
	Name string
}
```

CreateSessionOptions configures settings inherited by every session command.

## ExecOptions [#execoptions]

```go
type ExecOptions struct {
	// Cwd overrides the working directory. Empty starts in the user's home
	// directory when it is available (not with an explicit User), otherwise the
	// sandbox's working directory.
	Cwd string
	// Env adds environment variables. Nil omits env; an empty non-nil map sends {}.
	Env map[string]string
	// User overrides the OS user.
	User string
	// Shell overrides automatic bash/sh selection for shell commands.
	Shell string
	// Login selects a login shell; nil leaves it to the sandbox.
	Login *bool
	// Name is an optional live process alias.
	Name string
	// Tag groups this process for List and KillAll.
	Tag string
	// Timeout bounds waiting, not execution. Zero, WaitForever or NoTimeout waits indefinitely.
	// Expiry returns reason timed_out; reconnect ProcessID to observe or stop the process.
	// With output writers, the wait budget starts after creation. The create request
	// uses the client timeout unless Timeout is explicitly unlimited.
	Timeout time.Duration
	// ExecutionTimeout is a server deadline that kills the process tree. Zero,
	// NoTimeout, or a value above the longest timer every SDK shares (about
	// 24.8 days) means no deadline, as in the other SDKs.
	ExecutionTimeout time.Duration
	// KeepLogs defaults to on_exit_ttl. none is refused because output requires logs.
	KeepLogs ProcessKeepLogs
	// Stdout receives live stdout and newly recovered timeout snapshot output.
	// Calls are synchronous; writers must not block indefinitely.
	// A writer error stops delivery, attempts to stop the process with a detached
	// five-second budget, and returns a partial result with ProcessID alongside an
	// SDK error preserving the writer's cause through errors.Is. Cleanup failure
	// does not replace that error or confirm the process stopped; Reason is unknown.
	// Any failure after process creation returns a partial result with ProcessID
	// and unknown Reason, including without writers. Non-writer failures do not
	// stop the process or retry the stream. Reconnect ProcessID
	// to wait, resume logs from the last delivered cursor, or stop the process.
	Stdout io.Writer
	// Stderr receives live stderr, serialized with Stdout calls (the same writer is safe).
	// Writer failures have the same result and best-effort cleanup semantics as Stdout.
	Stderr io.Writer
}
```

ExecOptions configures a blocking command. Nil selects defaults.

## KillAllProcessesOptions [#killallprocessesoptions]

```go
type KillAllProcessesOptions struct {
	// Timeout, when non-zero, is positive and at most 60s, rounded up to milliseconds.
	// Zero keeps the server's 10s default; no unbounded sentinel is accepted.
	Timeout time.Duration
}
```

KillAllProcessesOptions bounds how long a tag-wide kill waits.

## KillProcessOptions [#killprocessoptions]

```go
type KillProcessOptions struct {
	// Signal defaults to TERM and must be a bare name, not SIGTERM.
	Signal ProcessSignal
	// EscalateAfter sends EscalateTo after this delay; nil disables escalation.
	// A pointer permits explicit immediate escalation (zero). The delay rounds up
	// to milliseconds and must be at most 10 minutes; otherwise Kill returns ErrBadRequest.
	EscalateAfter *time.Duration
	// EscalateTo defaults to KILL when EscalateAfter is set.
	EscalateTo ProcessSignal
}
```

KillProcessOptions selects a signal and optional escalation.

## ListProcessesOptions [#listprocessesoptions]

```go
type ListProcessesOptions struct {
	// Tag selects only matching processes, even with older servers that ignore it.
	Tag string
	// State is running, terminal, or all; empty selects all.
	State ProcessListState
	// Kind filters by execution backend.
	Kind ProcessKind
	// SessionID filters by shell session or interpreter context.
	SessionID string
	// Name filters by live alias.
	Name string
	// PID filters by OS process ID; nil omits it. Values outside 0..2147483647
	// return ErrBadRequest before any request.
	PID *int
}
```

ListProcessesOptions filters the one-shot process list (not paginated by the server).

## LogChannel [#logchannel]

```go
type LogChannel string
```

LogChannel identifies process output. Future channels are kept in RawChannel.

```go
const (
	// LogChannelUnknown represents an unrecognized channel.
	LogChannelUnknown LogChannel = "unknown"
	// LogChannelStdout contains standard output.
	LogChannelStdout LogChannel = "stdout"
	// LogChannelStderr contains standard error.
	LogChannelStderr LogChannel = "stderr"
	// LogChannelPTY contains terminal output.
	LogChannelPTY LogChannel = "pty"
	// LogChannelSetup contains provisioning narration, not command output.
	LogChannelSetup LogChannel = "setup"
	// LogChannelDisplay contains interpreter display data.
	LogChannelDisplay LogChannel = "display"
	// LogChannelExecuteResult contains an interpreter cell's main result.
	LogChannelExecuteResult LogChannel = "execute_result"
	// LogChannelError contains a structured interpreter error.
	LogChannelError LogChannel = "error"
)
```

## LogEncoding [#logencoding]

```go
type LogEncoding string
```

LogEncoding selects text or standard padded base64 log payloads.

```go
const (
	// LogEncodingUnknown represents an unknown encoding.
	LogEncodingUnknown LogEncoding = "unknown"
	// LogEncodingText decodes UTF-8 per channel across frames (default).
	LogEncodingText LogEncoding = "text"
	// LogEncodingBase64 preserves exact bytes as standard padded base64.
	LogEncodingBase64 LogEncoding = "base64"
)
```

## LogFrame [#logframe]

```go
type LogFrame struct {
	// Cursor is the opaque resume position.
	Cursor string
	// Timestamp is when the frame was written.
	Timestamp time.Time
	// Channel is the normalized output channel.
	Channel LogChannel
	// RawChannel preserves the server's channel.
	RawChannel string
	// Data contains text or base64, according to Encoding.
	Data string
	// Encoding is the requested encoding (text by default).
	Encoding LogEncoding
	// RawEncoding preserves the selected encoding name.
	RawEncoding string
}
```

LogFrame is a replayable frame; Data uses the requested Encoding.

## PTYOptions [#ptyoptions]

```go
type PTYOptions struct {
	// Cwd is the working directory. Empty starts in the user's home directory
	// when it is available (not with an explicit User), otherwise the sandbox's
	// working directory.
	Cwd string
	// Env adds environment variables. Nil omits env and an empty non-nil map
	// sends {}, before PTY defaults are applied: both still add
	// TERM=xterm-256color unless explicitly set.
	Env map[string]string
	// Name is an optional live alias.
	Name string
	// Tag groups processes; it must be a safe 1..128-character identifier.
	Tag string
	// User overrides the sandbox's OS user.
	User string
	// Shell overrides automatic shell selection.
	Shell string
	// Login selects a login shell; nil leaves selection to the sandbox.
	Login *bool
	// Stdin defaults to ProcessStdinOpen.
	Stdin ProcessStdinMode
	// ExecutionTimeout is a server-side deadline. Zero, NoTimeout, or a value
	// above the longest timer every SDK shares (about 24.8 days) means no deadline.
	ExecutionTimeout time.Duration
	// KeepLogs defaults to ProcessKeepLogsUntilCleanup.
	KeepLogs ProcessKeepLogs
	// Terminal defaults to 80 columns and 24 rows. Each dimension is 1..65535;
	// Windows sandboxes accept at most 32767.
	Terminal *TerminalSize
}
```

PTYOptions configures a detached or connected terminal. Nil selects defaults.

## ProcessHandleJSON [#processhandlejson]

```go
type ProcessHandleJSON struct {
	// SandboxID identifies the owning sandbox.
	SandboxID string `json:"sandboxId"`
	// ProcessID identifies the process.
	ProcessID string `json:"processId"`
	// Kind is optional; unknown kinds reconnect without local verb restrictions.
	Kind ProcessKind `json:"kind,omitempty"`
}
```

ProcessHandleJSON is the credential-free, cross-SDK process identity.

## ProcessInfo [#processinfo]

```go
type ProcessInfo struct {
	WaitResult
	// ID is the stable process ID.
	ID string
	// Kind is the normalized execution backend.
	Kind ProcessKind
	// RawKind preserves the server's kind.
	RawKind string
	// State is the normalized execution state.
	State ProcessState
	// RawState preserves the server's state.
	RawState string
	// Cwd is the current working directory.
	Cwd string
	// Stdin is the normalized input mode.
	Stdin ProcessStdinMode
	// RawStdin preserves the server's input mode.
	RawStdin string
	// KeepLogs is the normalized retention policy.
	KeepLogs ProcessKeepLogs
	// RawKeepLogs preserves the server's retention policy.
	RawKeepLogs string
	// CreatedAt is the creation timestamp.
	CreatedAt time.Time
	// System marks protected system processes.
	System bool
	// Name is the optional live alias.
	Name string
	// Tag groups related processes; session commands inherit their shell's tag.
	Tag string
	// PID is the OS process ID, when reported.
	PID *int
	// SessionID is the owning shell or interpreter context.
	SessionID string
	// Argv is the shell-free argument vector, when reported.
	Argv []string
	// ShellCommand is the shell command, when reported.
	ShellCommand string
	// Code is the code cell, when reported.
	Code string
	// Language is the open interpreter language name.
	Language string
	// Shell is the requested shell.
	Shell string
	// ResolvedShell is the actual shell binary.
	ResolvedShell string
	// Login distinguishes absent from a reported false login-shell setting.
	Login *bool
	// User is the OS user.
	User string
	// ExecutionTimeout is the server execution deadline; nil means unreported.
	ExecutionTimeout *time.Duration
	// Terminal is the PTY size, when reported.
	Terminal *TerminalSize
	// StartedAt is zero until reported.
	StartedAt time.Time
	// ExitedAt is zero until reported.
	ExitedAt time.Time
	// TruncatedHead reports retention loss.
	TruncatedHead bool
	// FirstAvailableCursor identifies the oldest retained frame.
	FirstAvailableCursor string
	// LastCursor identifies the newest retained frame.
	LastCursor string
}
```

ProcessInfo is a caller-owned process metadata snapshot.

## ProcessKeepLogs [#processkeeplogs]

```go
type ProcessKeepLogs string
```

ProcessKeepLogs selects process record and log retention.

```go
const (
	// ProcessKeepLogsUnknown preserves future policies in RawKeepLogs.
	ProcessKeepLogsUnknown ProcessKeepLogs = "unknown"
	// ProcessKeepLogsOnExitTTL retains output for a while after exit (the exec default).
	ProcessKeepLogsOnExitTTL ProcessKeepLogs = "on_exit_ttl"
	// ProcessKeepLogsUntilCleanup retains output until Delete.
	ProcessKeepLogsUntilCleanup ProcessKeepLogs = "until_cleanup"
	// ProcessKeepLogsNone disables logs; blocking runs refuse this policy.
	ProcessKeepLogsNone ProcessKeepLogs = "none"
)
```

## ProcessKind [#processkind]

```go
type ProcessKind string
```

ProcessKind identifies the execution backend.

```go
const (
	// ProcessKindUnknown preserves future kinds in RawKind.
	ProcessKindUnknown ProcessKind = "unknown"
	// ProcessKindExec is a command.
	ProcessKindExec ProcessKind = "exec"
	// ProcessKindPTY is an interactive terminal.
	ProcessKindPTY ProcessKind = "pty"
	// ProcessKindCode is a kernel-backed code cell.
	ProcessKindCode ProcessKind = "code"
	// ProcessKindSession is a persistent shell.
	ProcessKindSession ProcessKind = "session"
)
```

## ProcessListState [#processliststate]

```go
type ProcessListState string
```

ProcessListState selects a process-list state filter, not a process lifecycle state.
The zero value omits the filter (all); unsupported values return ErrBadRequest.

```go
const (
	// ProcessListStateAll selects processes in every state.
	ProcessListStateAll ProcessListState = "all"
	// ProcessListStateRunning selects live processes.
	ProcessListStateRunning ProcessListState = "running"
	// ProcessListStateTerminal selects processes whose execution has ended.
	ProcessListStateTerminal ProcessListState = "terminal"
)
```

## ProcessLogEOFEvent [#processlogeofevent]

```go
type ProcessLogEOFEvent struct {
	// Cursor is the final resume position.
	Cursor string
}
```

ProcessLogEOFEvent marks a complete log stream.

## ProcessLogEvent [#processlogevent]

```go
type ProcessLogEvent interface {
	// contains filtered or unexported methods
}
```

ProcessLogEvent is a closed union of frame, terminal-state, retention-warning,
and EOF events. A stream error is yielded as err, not as an event.

## ProcessLogFrameEvent [#processlogframeevent]

```go
type ProcessLogFrameEvent struct {
	// Cursor is the event's resume position.
	Cursor string
	// Frame is the recorded output.
	Frame LogFrame
}
```

ProcessLogFrameEvent delivers one log frame.

## ProcessLogPage [#processlogpage]

```go
type ProcessLogPage struct {
	// Items contains this page's frames.
	Items []LogFrame
	// NextCursor resumes after this page.
	NextCursor string
	// TruncatedHead reports frames evicted before this page.
	TruncatedHead bool
	// EOF means execution ended and no frames follow.
	EOF bool
	// FirstAvailableCursor identifies the oldest retained frame after eviction.
	FirstAvailableCursor string
}
```

ProcessLogPage is one page of retained log frames.

## ProcessLogStateEvent [#processlogstateevent]

```go
type ProcessLogStateEvent struct {
	// Cursor is the event's resume position.
	Cursor string
	// Result reports only the outcome fields the server supplied.
	Result WaitResult
}
```

ProcessLogStateEvent reports a terminal process result.

## ProcessLogWarningEvent [#processlogwarningevent]

```go
type ProcessLogWarningEvent struct {
	// Cursor is the event's resume position.
	Cursor string
	// Message describes the warning.
	Message string
	// FirstAvailableCursor is the earliest retained frame.
	FirstAvailableCursor string
}
```

ProcessLogWarningEvent reports retention loss.

## ProcessLogsOptions [#processlogsoptions]

```go
type ProcessLogsOptions struct {
	// Cursor resumes after this position; empty begins at the retained head.
	Cursor string
	// Limit is the requested page size; zero uses the server default.
	Limit int
	// Encoding defaults to text.
	Encoding LogEncoding
}
```

ProcessLogsOptions selects a replay position and payload encoding.

## ProcessReason [#processreason]

```go
type ProcessReason string
```

ProcessReason reports why execution or a wait ended.

```go
const (
	// ProcessReasonUnknown means absent or unrecognized; see RawReason.
	ProcessReasonUnknown ProcessReason = "unknown"
	// ProcessReasonExited means the command exited normally, not necessarily successfully.
	ProcessReasonExited ProcessReason = "exited"
	// ProcessReasonSignaled means a signal ended execution.
	ProcessReasonSignaled ProcessReason = "signaled"
	// ProcessReasonTimedOut means the wait or execution deadline expired.
	ProcessReasonTimedOut ProcessReason = "timed_out"
	// ProcessReasonLost means execution was lost.
	ProcessReasonLost ProcessReason = "lost"
	// ProcessReasonFailed means execution failed.
	ProcessReasonFailed ProcessReason = "failed"
)
```

## ProcessResult [#processresult]

```go
type ProcessResult struct {
	WaitResult
	// ProcessID can be passed to Process.Connect to continue observing a timed-out run.
	ProcessID string
	// Stdout contains stdout (and PTY) frames only.
	Stdout string
	// Stderr contains stderr frames only.
	Stderr string
	// Output interleaves stdout/stderr/PTY frames in log order, excluding setup narration.
	Output string
	// Logs contains every retained frame used to collect this result.
	Logs []LogFrame
}
```

ProcessResult holds a command's terminal or timed-out result and retained output.
A non-zero ExitCode is NOT an error. Err from Exec/Run indicates invalid input,
a transport/protocol failure, cancellation, or a server error.

## ProcessSignal [#processsignal]

```go
type ProcessSignal string
```

ProcessSignal names a signal without the SIG prefix.

```go
const (
	// ProcessSignalUnknown preserves future signals in RawSignal.
	ProcessSignalUnknown ProcessSignal = "unknown"
	// ProcessSignalTerminate requests graceful termination.
	ProcessSignalTerminate ProcessSignal = "TERM"
	// ProcessSignalKill forces termination.
	ProcessSignalKill ProcessSignal = "KILL"
	// ProcessSignalInterrupt interrupts a command or code cell.
	ProcessSignalInterrupt ProcessSignal = "INT"
	// ProcessSignalHangup sends a hangup.
	ProcessSignalHangup ProcessSignal = "HUP"
	// ProcessSignalQuit sends a quit signal.
	ProcessSignalQuit ProcessSignal = "QUIT"
	// ProcessSignalUser1 sends the first user-defined signal.
	ProcessSignalUser1 ProcessSignal = "USR1"
	// ProcessSignalUser2 sends the second user-defined signal.
	ProcessSignalUser2 ProcessSignal = "USR2"
)
```

## ProcessStartOptions [#processstartoptions]

```go
type ProcessStartOptions struct {
	// Name is an optional live alias.
	Name string
	// Tag groups commands; 1..128 ASCII letters, digits, '.', '_' or '-', excluding '.' and '..'.
	Tag string
	// Cwd is the working directory. Empty starts in the user's home directory
	// when it is available (not with an explicit User), otherwise the sandbox's
	// working directory.
	Cwd string
	// Env adds environment variables. Nil omits env; an empty non-nil map sends {}.
	Env map[string]string
	// User overrides the OS user.
	User string
	// Shell overrides automatic shell selection (bash, otherwise sh).
	Shell string
	// Login selects a login shell; nil leaves selection to the sandbox.
	Login *bool
	// Stdin defaults to closed. Use open for Write/CloseStdin.
	Stdin ProcessStdinMode
	// ExecutionTimeout kills the process tree on expiry. Zero, NoTimeout, or a
	// value above the longest timer every SDK shares (about 24.8 days) means no
	// deadline, as in the other SDKs.
	ExecutionTimeout time.Duration
	// KeepLogs defaults to on_exit_ttl.
	KeepLogs ProcessKeepLogs
}
```

ProcessStartOptions configures a background command; nil selects all defaults.

## ProcessState [#processstate]

```go
type ProcessState string
```

ProcessState is the last observed execution state.

```go
const (
	// ProcessStateUnknown preserves future states in RawState.
	ProcessStateUnknown ProcessState = "unknown"
	// ProcessStateStarting means execution is queued or starting.
	ProcessStateStarting ProcessState = "starting"
	// ProcessStateProvisioning means the kernel is being prepared.
	ProcessStateProvisioning ProcessState = "provisioning"
	// ProcessStateRunning means execution has begun.
	ProcessStateRunning ProcessState = "running"
	// ProcessStateTerminal means execution has ended.
	ProcessStateTerminal ProcessState = "terminal"
)
```

## ProcessStdinMode [#processstdinmode]

```go
type ProcessStdinMode string
```

ProcessStdinMode selects whether a process accepts input.

```go
const (
	// ProcessStdinUnknown preserves future stdin modes in RawStdin.
	ProcessStdinUnknown ProcessStdinMode = "unknown"
	// ProcessStdinClosed starts with stdin closed (the exec default).
	ProcessStdinClosed ProcessStdinMode = "closed"
	// ProcessStdinOpen enables Write and CloseStdin.
	ProcessStdinOpen ProcessStdinMode = "open"
)
```

## SessionJSON [#sessionjson]

```go
type SessionJSON struct {
	// SandboxID identifies the owning sandbox.
	SandboxID string `json:"sandboxId"`
	// SessionID identifies the persistent shell process.
	SessionID string `json:"sessionId"`
}
```

SessionJSON is the credential-free, cross-SDK shell-session identity.

## SessionRunOptions [#sessionrunoptions]

```go
type SessionRunOptions struct {
	// Name is an optional command alias.
	Name string
	// ExecutionTimeout stops the command on expiry, normally preserving the shell.
	// Zero, NoTimeout, or a value above the longest timer every SDK shares (about
	// 24.8 days) disables it.
	ExecutionTimeout time.Duration
	// KeepLogs defaults to on_exit_ttl; none is refused.
	KeepLogs ProcessKeepLogs
	// Timeout bounds the caller's wait, without killing. See ExecOptions.Timeout
	// for defaults and streaming creation semantics.
	Timeout time.Duration
	// Stdout receives live output; writes are serialized with Stderr.
	// Failures preserve the partial result as described on ExecOptions.Stdout.
	Stdout io.Writer
	// Stderr receives live error output.
	Stderr io.Writer
}
```

SessionRunOptions configures a blocking session command.

## SessionStartOptions [#sessionstartoptions]

```go
type SessionStartOptions struct {
	// Name is an optional command alias.
	Name string
	// Stdin defaults to closed; open permits writing through the returned handle.
	Stdin ProcessStdinMode
	// ExecutionTimeout starts when the command starts, after earlier queued commands.
	// Zero, NoTimeout, or a value above the longest timer every SDK shares (about
	// 24.8 days) disables it. The shell normally survives a command timeout.
	ExecutionTimeout time.Duration
	// KeepLogs defaults to on_exit_ttl.
	KeepLogs ProcessKeepLogs
}
```

SessionStartOptions configures one queued command, not the persistent shell.

## TerminalSize [#terminalsize]

```go
type TerminalSize struct {
	// Cols is the number of columns.
	Cols int `json:"cols"`
	// Rows is the number of rows.
	Rows int `json:"rows"`
}
```

TerminalSize is a terminal's size in character cells; each dimension is 1..65535.

## WaitProcessOptions [#waitprocessoptions]

```go
type WaitProcessOptions struct {
	// Timeout defaults to unlimited; WaitForever also waits until terminal.
	// Expiry returns reason timed_out without killing the process; ctx cancellation is an error.
	Timeout time.Duration
}
```

WaitProcessOptions bounds observation, not execution.

## WaitResult [#waitresult]

```go
type WaitResult struct {
	// Reason is the normalized outcome; unknown when unreported.
	Reason ProcessReason
	// RawReason is the server's outcome verbatim, or empty when absent.
	RawReason string
	// ExitCode is nil when unreported; non-zero is not an SDK error.
	ExitCode *int
	// Signal is the normalized bare signal name, or empty when absent.
	Signal ProcessSignal
	// RawSignal is the server's signal without its SIG prefix.
	RawSignal string
}
```

WaitResult reports only what the sandbox reported. A nil ExitCode means absent,
never an assumed success. A caller wait timeout does not stop execution.
