CodeRunParams
Parameters for code execution.
Properties:
argv?
string[] - Command line argumentsenv?
Record<string, string> - Environment variables
Constructors
new CodeRunParams()
new CodeRunParams(): CodeRunParams
Returns:
CodeRunParams
Process
Handles process and code execution within a Sandbox.
Constructors
new Process()
new Process( sandboxId: string, clientConfig: Configuration, codeToolbox: SandboxCodeToolbox, toolboxApi: ToolboxApi, getPreviewLink: (port: number) => Promise<PortPreviewUrl>): Process
Parameters:
sandboxId
stringclientConfig
ConfigurationcodeToolbox
SandboxCodeToolboxtoolboxApi
ToolboxApigetPreviewLink
(port: number) => Promise<PortPreviewUrl>
Returns:
Process
Methods
codeRun()
codeRun( code: string, params?: CodeRunParams,timeout?: number): Promise<ExecuteResponse>
Executes code in the Sandbox using the appropriate language runtime.
Parameters:
code
string - Code to executeparams?
CodeRunParams - Parameters for code executiontimeout?
number - Maximum time in seconds to wait for execution to complete
Returns:
Promise<ExecuteResponse>
- Code execution results containing:- exitCode: The execution’s exit status
- result: Standard output from the code
- artifacts: ExecutionArtifacts object containing
stdout
(same as result) andcharts
(matplotlib charts metadata)
Examples:
// Run TypeScript codeconst response = await process.codeRun(` const x = 10; const y = 20; console.log(\`Sum: \${x + y}\`);`);console.log(response.artifacts.stdout); // Prints: Sum: 30
// Run Python code with matplotlibconst response = await process.codeRun(`import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(0, 10, 30)y = np.sin(x)
plt.figure(figsize=(8, 5))plt.plot(x, y, 'b-', linewidth=2)plt.title('Line Chart')plt.xlabel('X-axis (seconds)')plt.ylabel('Y-axis (amplitude)')plt.grid(True)plt.show()`);
if (response.artifacts?.charts) { const chart = response.artifacts.charts[0];
console.log(`Type: ${chart.type}`); console.log(`Title: ${chart.title}`); if (chart.type === ChartType.LINE) { const lineChart = chart as LineChart console.log('X Label:', lineChart.x_label) console.log('Y Label:', lineChart.y_label) console.log('X Ticks:', lineChart.x_ticks) console.log('Y Ticks:', lineChart.y_ticks) console.log('X Tick Labels:', lineChart.x_tick_labels) console.log('Y Tick Labels:', lineChart.y_tick_labels) console.log('X Scale:', lineChart.x_scale) console.log('Y Scale:', lineChart.y_scale) console.log('Elements:') console.dir(lineChart.elements, { depth: null }) }}
connectPty()
connectPty(sessionId: string, options?: PtyConnectOptions): Promise<PtyHandle>
Connect to an existing PTY session in the sandbox.
Establishes a WebSocket connection to an existing PTY session, allowing you to interact with a previously created terminal session.
Parameters:
sessionId
string - ID of the PTY session to connect tooptions?
PtyConnectOptions - Options for the connection including data handler
Returns:
Promise<PtyHandle>
- PTY handle for managing the session
Example:
// Connect to an existing PTY sessionconst handle = await process.connectPty('my-session', { onData: (data) => { // Handle terminal output const text = new TextDecoder().decode(data); process.stdout.write(text); },});
// Wait for connection to be establishedawait handle.waitForConnection();
// Send commands to the existing sessionawait handle.sendInput('pwd\n');await handle.sendInput('ls -la\n');await handle.sendInput('exit\n');
// Wait for completionconst result = await handle.wait();console.log(`Session exited with code: ${result.exitCode}`);
// Clean upawait handle.disconnect();
createPty()
createPty(options?: PtyCreateOptions & PtyConnectOptions): Promise<PtyHandle>
Create a new PTY (pseudo-terminal) session in the sandbox.
Creates an interactive terminal session that can execute commands and handle user input. The PTY session behaves like a real terminal, supporting features like command history.
Parameters:
options?
PtyCreateOptions & PtyConnectOptions - PTY session configuration including creation and connection options
Returns:
Promise<PtyHandle>
- PTY handle for managing the session
Example:
// Create a PTY session with custom configurationconst ptyHandle = await process.createPty({ id: 'my-interactive-session', cwd: '/workspace', envs: { TERM: 'xterm-256color', LANG: 'en_US.UTF-8' }, cols: 120, rows: 30, onData: (data) => { // Handle terminal output const text = new TextDecoder().decode(data); process.stdout.write(text); },});
// Wait for connection to be establishedawait ptyHandle.waitForConnection();
// Send commands to the terminalawait ptyHandle.sendInput('ls -la\n');await ptyHandle.sendInput('echo "Hello, PTY!"\n');await ptyHandle.sendInput('exit\n');
// Wait for completion and get resultconst result = await ptyHandle.wait();console.log(`PTY session completed with exit code: ${result.exitCode}`);
// Clean upawait ptyHandle.disconnect();
createSession()
createSession(sessionId: string): Promise<void>
Creates a new long-running background session in the Sandbox.
Sessions are background processes that maintain state between commands, making them ideal for scenarios requiring multiple related commands or persistent environment setup. You can run long-running commands and monitor process status.
Parameters:
sessionId
string - Unique identifier for the new session
Returns:
Promise<void>
Example:
// Create a new sessionconst sessionId = 'my-session';await process.createSession(sessionId);const session = await process.getSession(sessionId);// Do work...await process.deleteSession(sessionId);
deleteSession()
deleteSession(sessionId: string): Promise<void>
Delete a session from the Sandbox.
Parameters:
sessionId
string - Unique identifier of the session to delete
Returns:
Promise<void>
Example:
// Clean up a completed sessionawait process.deleteSession('my-session');
executeCommand()
executeCommand( command: string, cwd?: string, env?: Record<string, string>,timeout?: number): Promise<ExecuteResponse>
Executes a shell command in the Sandbox.
Parameters:
command
string - Shell command to executecwd?
string - Working directory for command execution. If not specified, uses the sandbox working directory.env?
Record<string, string> - Environment variables to set for the commandtimeout?
number - Maximum time in seconds to wait for the command to complete. 0 means wait indefinitely.
Returns:
Promise<ExecuteResponse>
- Command execution results containing:- exitCode: The command’s exit status
- result: Standard output from the command
- artifacts: ExecutionArtifacts object containing
stdout
(same as result) andcharts
(matplotlib charts metadata)
Examples:
// Simple commandconst response = await process.executeCommand('echo "Hello"');console.log(response.artifacts.stdout); // Prints: Hello
// Command with working directoryconst result = await process.executeCommand('ls', 'workspace/src');
// Command with timeoutconst result = await process.executeCommand('sleep 10', undefined, 5);
executeSessionCommand()
executeSessionCommand( sessionId: string, req: SessionExecuteRequest,timeout?: number): Promise<SessionExecuteResponse>
Executes a command in an existing session.
Parameters:
sessionId
string - Unique identifier of the session to usereq
SessionExecuteRequest - Command execution request containing:- command: The command to execute
- runAsync: Whether to execute asynchronously
timeout?
number - Timeout in seconds
Returns:
Promise<SessionExecuteResponse>
- Command execution results containing:- cmdId: Unique identifier for the executed command
- output: Combined command output (stdout and stderr) (if synchronous execution)
- stdout: Standard output from the command
- stderr: Standard error from the command
- exitCode: Command exit status (if synchronous execution)
Example:
// Execute commands in sequence, maintaining stateconst sessionId = 'my-session';
// Change directoryawait process.executeSessionCommand(sessionId, { command: 'cd /home/daytona'});
// Run command in new directoryconst result = await process.executeSessionCommand(sessionId, { command: 'pwd'});console.log('[STDOUT]:', result.stdout);console.log('[STDERR]:', result.stderr);
getPtySessionInfo()
getPtySessionInfo(sessionId: string): Promise<PtySessionInfo>
Get detailed information about a specific PTY session.
Retrieves comprehensive information about a PTY session including its current state, configuration, and metadata.
Parameters:
sessionId
string - ID of the PTY session to retrieve information for
Returns:
Promise<PtySessionInfo>
- PTY session information
Throws:
If the PTY session doesn’t exist
Example:
// Get details about a specific PTY sessionconst session = await process.getPtySessionInfo('my-session');
console.log(`Session ID: ${session.id}`);console.log(`Active: ${session.active}`);console.log(`Working Directory: ${session.cwd}`);console.log(`Terminal Size: ${session.cols}x${session.rows}`);
if (session.processId) { console.log(`Process ID: ${session.processId}`);}
getSession()
getSession(sessionId: string): Promise<Session>
Get a session in the sandbox.
Parameters:
sessionId
string - Unique identifier of the session to retrieve
Returns:
Promise<Session>
- Session information including:- sessionId: The session’s unique identifier
- commands: List of commands executed in the session
Example:
const session = await process.getSession('my-session');session.commands.forEach(cmd => { console.log(`Command: ${cmd.command}`);});
getSessionCommand()
getSessionCommand(sessionId: string, commandId: string): Promise<Command>
Gets information about a specific command executed in a session.
Parameters:
sessionId
string - Unique identifier of the sessioncommandId
string - Unique identifier of the command
Returns:
Promise<Command>
- Command information including:- id: The command’s unique identifier
- command: The executed command string
- exitCode: Command’s exit status (if completed)
Example:
const cmd = await process.getSessionCommand('my-session', 'cmd-123');if (cmd.exitCode === 0) { console.log(`Command ${cmd.command} completed successfully`);}
getSessionCommandLogs()
Call Signature
getSessionCommandLogs(sessionId: string, commandId: string): Promise<SessionCommandLogsResponse>
Get the logs for a command executed in a session.
Parameters:
sessionId
string - Unique identifier of the sessioncommandId
string - Unique identifier of the command
Returns:
Promise<SessionCommandLogsResponse>
- Command logs containing: output (combined stdout and stderr), stdout and stderr
Example:
const logs = await process.getSessionCommandLogs('my-session', 'cmd-123');console.log('[STDOUT]:', logs.stdout);console.log('[STDERR]:', logs.stderr);
Call Signature
getSessionCommandLogs( sessionId: string, commandId: string, onStdout: (chunk: string) => void,onStderr: (chunk: string) => void): Promise<void>
Asynchronously retrieve and process the logs for a command executed in a session as they become available.
Parameters:
sessionId
string - Unique identifier of the sessioncommandId
string - Unique identifier of the commandonStdout
(chunk: string) => void - Callback function to handle stdout log chunksonStderr
(chunk: string) => void - Callback function to handle stderr log chunks
Returns:
Promise<void>
Example:
const logs = await process.getSessionCommandLogs('my-session', 'cmd-123', (chunk) => { console.log('[STDOUT]:', chunk);}, (chunk) => { console.log('[STDERR]:', chunk);});
killPtySession()
killPtySession(sessionId: string): Promise<void>
Kill a PTY session and terminate its associated process.
Forcefully terminates the PTY session and cleans up all associated resources. This will close any active connections and kill the underlying shell process.
Parameters:
sessionId
string - ID of the PTY session to kill
Returns:
Promise<void>
Throws:
If the PTY session doesn’t exist or cannot be killed
Note
This operation is irreversible. Any unsaved work in the terminal session will be lost.
Example:
// Kill a specific PTY sessionawait process.killPtySession('my-session');
// Verify the session is no longer activetry { const info = await process.getPtySessionInfo('my-session'); console.log(`Session still exists but active: ${info.active}`);} catch (error) { console.log('Session has been completely removed');}
listPtySessions()
listPtySessions(): Promise<PtySessionInfo[]>
List all PTY sessions in the sandbox.
Retrieves information about all PTY sessions, both active and inactive, that have been created in this sandbox.
Returns:
Promise<PtySessionInfo[]>
- Array of PTY session information
Example:
// List all PTY sessionsconst sessions = await process.listPtySessions();
for (const session of sessions) { console.log(`Session ID: ${session.id}`); console.log(`Active: ${session.active}`); console.log(`Created: ${session.createdAt}`); } console.log('---');}
listSessions()
listSessions(): Promise<Session[]>
Lists all active sessions in the Sandbox.
Returns:
Promise<Session[]>
- Array of active sessions
Example:
const sessions = await process.listSessions();sessions.forEach(session => { console.log(`Session ${session.sessionId}:`); session.commands.forEach(cmd => { console.log(`- ${cmd.command} (${cmd.exitCode})`); });});
resizePtySession()
resizePtySession( sessionId: string, cols: number,rows: number): Promise<PtySessionInfo>
Resize a PTY session’s terminal dimensions.
Changes the terminal size of an active PTY session. This is useful when the client terminal is resized or when you need to adjust the display for different output requirements.
Parameters:
sessionId
string - ID of the PTY session to resizecols
number - New number of terminal columnsrows
number - New number of terminal rows
Returns:
Promise<PtySessionInfo>
- Updated session information reflecting the new terminal size
Throws:
If the PTY session doesn’t exist or resize operation fails
Note
The resize operation will send a SIGWINCH signal to the shell process, allowing terminal applications to adapt to the new size.
Example:
// Resize a PTY session to a larger terminalconst updatedInfo = await process.resizePtySession('my-session', 150, 40);console.log(`Terminal resized to ${updatedInfo.cols}x${updatedInfo.rows}`);
// You can also use the PtyHandle's resize methodawait ptyHandle.resize(150, 40); // cols, rows
SessionCommandLogsResponse
Properties:
output?
stringstderr?
stringstdout?
string
SessionExecuteResponse
Extends:
Properties:
-
cmdId?
string - The ID of the executed command- Inherited from:
SessionExecuteResponse.cmdId
- Inherited from:
-
exitCode?
number - The exit code of the executed command- Inherited from:
SessionExecuteResponse.exitCode
- Inherited from:
-
output?
string - The output of the executed command marked with stdout and stderr prefixes- Inherited from:
SessionExecuteResponse.output
- Inherited from:
-
stderr?
string -
stdout?
string -
SessionExecuteResponse
MAX_PREFIX_LEN
const MAX_PREFIX_LEN: number;
STDERR_PREFIX_BYTES
const STDERR_PREFIX_BYTES: Uint8Array<ArrayBuffer>;
STDOUT_PREFIX_BYTES
const STDOUT_PREFIX_BYTES: Uint8Array<ArrayBuffer>;