@daytonaio/sdk 0.175.0 → 0.178.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/cjs/CodeInterpreter.d.ts +3 -2
  2. package/cjs/CodeInterpreter.js.map +1 -1
  3. package/cjs/ComputerUse.d.ts +104 -2
  4. package/cjs/ComputerUse.js +851 -763
  5. package/cjs/ComputerUse.js.map +1 -1
  6. package/cjs/Daytona.d.ts +4 -3
  7. package/cjs/Daytona.js +429 -443
  8. package/cjs/Daytona.js.map +1 -1
  9. package/cjs/FileSystem.d.ts +2 -2
  10. package/cjs/FileSystem.js +491 -521
  11. package/cjs/FileSystem.js.map +1 -1
  12. package/cjs/Git.d.ts +2 -1
  13. package/cjs/Git.js +287 -310
  14. package/cjs/Git.js.map +1 -1
  15. package/cjs/LspServer.d.ts +2 -1
  16. package/cjs/LspServer.js +209 -226
  17. package/cjs/LspServer.js.map +1 -1
  18. package/cjs/ObjectStorage.js +170 -166
  19. package/cjs/ObjectStorage.js.map +1 -1
  20. package/cjs/Process.d.ts +4 -3
  21. package/cjs/Process.js +562 -600
  22. package/cjs/Process.js.map +1 -1
  23. package/cjs/PtyHandle.d.ts +2 -2
  24. package/cjs/PtyHandle.js +327 -338
  25. package/cjs/PtyHandle.js.map +1 -1
  26. package/cjs/Sandbox.d.ts +4 -3
  27. package/cjs/Sandbox.js +756 -821
  28. package/cjs/Sandbox.js.map +1 -1
  29. package/cjs/Snapshot.d.ts +3 -2
  30. package/cjs/Snapshot.js +203 -213
  31. package/cjs/Snapshot.js.map +1 -1
  32. package/cjs/Volume.d.ts +2 -1
  33. package/cjs/Volume.js +90 -92
  34. package/cjs/Volume.js.map +1 -1
  35. package/cjs/errors/DaytonaError.d.ts +2 -1
  36. package/cjs/errors/DaytonaError.js.map +1 -1
  37. package/cjs/index.d.ts +2 -2
  38. package/cjs/index.js +2 -1
  39. package/cjs/index.js.map +1 -1
  40. package/cjs/types/CodeInterpreter.d.ts +1 -1
  41. package/cjs/utils/Binary.js +14 -2
  42. package/cjs/utils/Binary.js.map +1 -1
  43. package/cjs/utils/otel.decorator.d.ts +7 -8
  44. package/cjs/utils/otel.decorator.js +24 -30
  45. package/cjs/utils/otel.decorator.js.map +1 -1
  46. package/esm/CodeInterpreter.d.ts +3 -2
  47. package/esm/CodeInterpreter.js.map +1 -1
  48. package/esm/ComputerUse.d.ts +104 -2
  49. package/esm/ComputerUse.js +857 -763
  50. package/esm/ComputerUse.js.map +1 -1
  51. package/esm/Daytona.d.ts +4 -3
  52. package/esm/Daytona.js +431 -444
  53. package/esm/Daytona.js.map +1 -1
  54. package/esm/FileSystem.d.ts +2 -2
  55. package/esm/FileSystem.js +493 -522
  56. package/esm/FileSystem.js.map +1 -1
  57. package/esm/Git.d.ts +2 -1
  58. package/esm/Git.js +289 -311
  59. package/esm/Git.js.map +1 -1
  60. package/esm/LspServer.d.ts +2 -1
  61. package/esm/LspServer.js +211 -227
  62. package/esm/LspServer.js.map +1 -1
  63. package/esm/ObjectStorage.js +172 -167
  64. package/esm/ObjectStorage.js.map +1 -1
  65. package/esm/Process.d.ts +4 -3
  66. package/esm/Process.js +564 -601
  67. package/esm/Process.js.map +1 -1
  68. package/esm/PtyHandle.d.ts +2 -2
  69. package/esm/PtyHandle.js +329 -339
  70. package/esm/PtyHandle.js.map +1 -1
  71. package/esm/Sandbox.d.ts +4 -3
  72. package/esm/Sandbox.js +759 -823
  73. package/esm/Sandbox.js.map +1 -1
  74. package/esm/Snapshot.d.ts +3 -2
  75. package/esm/Snapshot.js +206 -215
  76. package/esm/Snapshot.js.map +1 -1
  77. package/esm/Volume.d.ts +2 -1
  78. package/esm/Volume.js +92 -93
  79. package/esm/Volume.js.map +1 -1
  80. package/esm/errors/DaytonaError.d.ts +2 -1
  81. package/esm/errors/DaytonaError.js.map +1 -1
  82. package/esm/index.d.ts +2 -2
  83. package/esm/index.js +1 -1
  84. package/esm/index.js.map +1 -1
  85. package/esm/types/CodeInterpreter.d.ts +1 -1
  86. package/esm/utils/Binary.js +14 -2
  87. package/esm/utils/Binary.js.map +1 -1
  88. package/esm/utils/otel.decorator.d.ts +7 -8
  89. package/esm/utils/otel.decorator.js +26 -32
  90. package/esm/utils/otel.decorator.js.map +1 -1
  91. package/package.json +3 -3
package/esm/Process.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Copyright 2025 Daytona Platforms Inc.
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import { __decorate, __metadata } from "tslib";
5
+ import { __esDecorate, __runInitializers } from "tslib";
6
6
  import { parseChart } from './types/Charts.js';
7
7
  import { stdDemuxStream } from './utils/Stream.js';
8
8
  import { PtyHandle } from './PtyHandle.js';
@@ -30,613 +30,576 @@ export class CodeRunParams {
30
30
  *
31
31
  * @class
32
32
  */
33
- export class Process {
34
- clientConfig;
35
- apiClient;
36
- getPreviewToken;
37
- language;
38
- constructor(clientConfig, apiClient, getPreviewToken, language) {
39
- this.clientConfig = clientConfig;
40
- this.apiClient = apiClient;
41
- this.getPreviewToken = getPreviewToken;
42
- this.language = language;
43
- }
44
- /**
45
- * Executes a shell command in the Sandbox.
46
- *
47
- * @param {string} command - Shell command to execute
48
- * @param {string} [cwd] - Working directory for command execution. If not specified, uses the sandbox working directory.
49
- * @param {Record<string, string>} [env] - Environment variables to set for the command
50
- * @param {number} [timeout] - Maximum time in seconds to wait for the command to complete.
51
- * @returns {Promise<ExecuteResponse>} Command execution results containing:
52
- * - exitCode: The command's exit status
53
- * - result: Standard output from the command
54
- * - artifacts: ExecutionArtifacts object containing `stdout` (same as result) and `charts` (matplotlib charts metadata)
55
- *
56
- * @example
57
- * // Simple command
58
- * const response = await process.executeCommand('echo "Hello"');
59
- * console.log(response.artifacts.stdout); // Prints: Hello
60
- *
61
- * @example
62
- * // Command with working directory
63
- * const result = await process.executeCommand('ls', 'workspace/src');
64
- *
65
- * @example
66
- * // Command with timeout
67
- * const result = await process.executeCommand('sleep 10', undefined, 5);
68
- */
69
- async executeCommand(command, cwd, env, timeout) {
70
- const response = await this.apiClient.executeCommand({
71
- command,
72
- timeout,
73
- cwd: cwd,
74
- envs: env && Object.keys(env).length ? env : undefined,
75
- });
76
- const result = response.data.result ?? '';
77
- return {
78
- exitCode: response.data.exitCode ?? response.data.code,
79
- result,
80
- artifacts: {
81
- stdout: result,
82
- },
83
- };
84
- }
85
- /**
86
- * Executes code in the Sandbox using the appropriate language runtime.
87
- *
88
- * @param {string} code - Code to execute
89
- * @param {CodeRunParams} params - Parameters for code execution
90
- * @param {number} [timeout] - Maximum time in seconds to wait for execution to complete
91
- * @returns {Promise<ExecuteResponse>} Code execution results containing:
92
- * - exitCode: The execution's exit status
93
- * - result: Standard output from the code
94
- * - artifacts: ExecutionArtifacts object containing `stdout` (same as result) and `charts` (matplotlib charts metadata)
95
- *
96
- * @example
97
- * // Run TypeScript code
98
- * const response = await process.codeRun(`
99
- * const x = 10;
100
- * const y = 20;
101
- * console.log(\`Sum: \${x + y}\`);
102
- * `);
103
- * console.log(response.artifacts.stdout); // Prints: Sum: 30
104
- *
105
- * @example
106
- * // Run Python code with matplotlib
107
- * const response = await process.codeRun(`
108
- * import matplotlib.pyplot as plt
109
- * import numpy as np
110
- *
111
- * x = np.linspace(0, 10, 30)
112
- * y = np.sin(x)
113
- *
114
- * plt.figure(figsize=(8, 5))
115
- * plt.plot(x, y, 'b-', linewidth=2)
116
- * plt.title('Line Chart')
117
- * plt.xlabel('X-axis (seconds)')
118
- * plt.ylabel('Y-axis (amplitude)')
119
- * plt.grid(True)
120
- * plt.show()
121
- * `);
122
- *
123
- * if (response.artifacts?.charts) {
124
- * const chart = response.artifacts.charts[0];
125
- *
126
- * console.log(`Type: ${chart.type}`);
127
- * console.log(`Title: ${chart.title}`);
128
- * if (chart.type === ChartType.LINE) {
129
- * const lineChart = chart as LineChart
130
- * console.log('X Label:', lineChart.x_label)
131
- * console.log('Y Label:', lineChart.y_label)
132
- * console.log('X Ticks:', lineChart.x_ticks)
133
- * console.log('Y Ticks:', lineChart.y_ticks)
134
- * console.log('X Tick Labels:', lineChart.x_tick_labels)
135
- * console.log('Y Tick Labels:', lineChart.y_tick_labels)
136
- * console.log('X Scale:', lineChart.x_scale)
137
- * console.log('Y Scale:', lineChart.y_scale)
138
- * console.log('Elements:')
139
- * console.dir(lineChart.elements, { depth: null })
140
- * }
141
- * }
142
- */
143
- async codeRun(code, params, timeout) {
144
- if (!this.language) {
145
- throw new Error('Code language is required for codeRun');
33
+ let Process = (() => {
34
+ let _instanceExtraInitializers = [];
35
+ let _executeCommand_decorators;
36
+ let _codeRun_decorators;
37
+ let _createSession_decorators;
38
+ let _getSessionCommand_decorators;
39
+ let _executeSessionCommand_decorators;
40
+ let _getSessionCommandLogs_decorators;
41
+ let _getEntrypointLogs_decorators;
42
+ let _listSessions_decorators;
43
+ let _deleteSession_decorators;
44
+ let _createPty_decorators;
45
+ let _connectPty_decorators;
46
+ let _listPtySessions_decorators;
47
+ let _getPtySessionInfo_decorators;
48
+ let _killPtySession_decorators;
49
+ let _resizePtySession_decorators;
50
+ return class Process {
51
+ static {
52
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
53
+ _executeCommand_decorators = [WithInstrumentation()];
54
+ _codeRun_decorators = [WithInstrumentation()];
55
+ _createSession_decorators = [WithInstrumentation()];
56
+ _getSessionCommand_decorators = [WithInstrumentation()];
57
+ _executeSessionCommand_decorators = [WithInstrumentation()];
58
+ _getSessionCommandLogs_decorators = [WithInstrumentation()];
59
+ _getEntrypointLogs_decorators = [WithInstrumentation()];
60
+ _listSessions_decorators = [WithInstrumentation()];
61
+ _deleteSession_decorators = [WithInstrumentation()];
62
+ _createPty_decorators = [WithInstrumentation()];
63
+ _connectPty_decorators = [WithInstrumentation()];
64
+ _listPtySessions_decorators = [WithInstrumentation()];
65
+ _getPtySessionInfo_decorators = [WithInstrumentation()];
66
+ _killPtySession_decorators = [WithInstrumentation()];
67
+ _resizePtySession_decorators = [WithInstrumentation()];
68
+ __esDecorate(this, null, _executeCommand_decorators, { kind: "method", name: "executeCommand", static: false, private: false, access: { has: obj => "executeCommand" in obj, get: obj => obj.executeCommand }, metadata: _metadata }, null, _instanceExtraInitializers);
69
+ __esDecorate(this, null, _codeRun_decorators, { kind: "method", name: "codeRun", static: false, private: false, access: { has: obj => "codeRun" in obj, get: obj => obj.codeRun }, metadata: _metadata }, null, _instanceExtraInitializers);
70
+ __esDecorate(this, null, _createSession_decorators, { kind: "method", name: "createSession", static: false, private: false, access: { has: obj => "createSession" in obj, get: obj => obj.createSession }, metadata: _metadata }, null, _instanceExtraInitializers);
71
+ __esDecorate(this, null, _getSessionCommand_decorators, { kind: "method", name: "getSessionCommand", static: false, private: false, access: { has: obj => "getSessionCommand" in obj, get: obj => obj.getSessionCommand }, metadata: _metadata }, null, _instanceExtraInitializers);
72
+ __esDecorate(this, null, _executeSessionCommand_decorators, { kind: "method", name: "executeSessionCommand", static: false, private: false, access: { has: obj => "executeSessionCommand" in obj, get: obj => obj.executeSessionCommand }, metadata: _metadata }, null, _instanceExtraInitializers);
73
+ __esDecorate(this, null, _getSessionCommandLogs_decorators, { kind: "method", name: "getSessionCommandLogs", static: false, private: false, access: { has: obj => "getSessionCommandLogs" in obj, get: obj => obj.getSessionCommandLogs }, metadata: _metadata }, null, _instanceExtraInitializers);
74
+ __esDecorate(this, null, _getEntrypointLogs_decorators, { kind: "method", name: "getEntrypointLogs", static: false, private: false, access: { has: obj => "getEntrypointLogs" in obj, get: obj => obj.getEntrypointLogs }, metadata: _metadata }, null, _instanceExtraInitializers);
75
+ __esDecorate(this, null, _listSessions_decorators, { kind: "method", name: "listSessions", static: false, private: false, access: { has: obj => "listSessions" in obj, get: obj => obj.listSessions }, metadata: _metadata }, null, _instanceExtraInitializers);
76
+ __esDecorate(this, null, _deleteSession_decorators, { kind: "method", name: "deleteSession", static: false, private: false, access: { has: obj => "deleteSession" in obj, get: obj => obj.deleteSession }, metadata: _metadata }, null, _instanceExtraInitializers);
77
+ __esDecorate(this, null, _createPty_decorators, { kind: "method", name: "createPty", static: false, private: false, access: { has: obj => "createPty" in obj, get: obj => obj.createPty }, metadata: _metadata }, null, _instanceExtraInitializers);
78
+ __esDecorate(this, null, _connectPty_decorators, { kind: "method", name: "connectPty", static: false, private: false, access: { has: obj => "connectPty" in obj, get: obj => obj.connectPty }, metadata: _metadata }, null, _instanceExtraInitializers);
79
+ __esDecorate(this, null, _listPtySessions_decorators, { kind: "method", name: "listPtySessions", static: false, private: false, access: { has: obj => "listPtySessions" in obj, get: obj => obj.listPtySessions }, metadata: _metadata }, null, _instanceExtraInitializers);
80
+ __esDecorate(this, null, _getPtySessionInfo_decorators, { kind: "method", name: "getPtySessionInfo", static: false, private: false, access: { has: obj => "getPtySessionInfo" in obj, get: obj => obj.getPtySessionInfo }, metadata: _metadata }, null, _instanceExtraInitializers);
81
+ __esDecorate(this, null, _killPtySession_decorators, { kind: "method", name: "killPtySession", static: false, private: false, access: { has: obj => "killPtySession" in obj, get: obj => obj.killPtySession }, metadata: _metadata }, null, _instanceExtraInitializers);
82
+ __esDecorate(this, null, _resizePtySession_decorators, { kind: "method", name: "resizePtySession", static: false, private: false, access: { has: obj => "resizePtySession" in obj, get: obj => obj.resizePtySession }, metadata: _metadata }, null, _instanceExtraInitializers);
83
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
146
84
  }
147
- const request = {
148
- code,
149
- language: this.language,
150
- argv: params?.argv,
151
- envs: params?.env,
152
- timeout,
153
- };
154
- const response = await this.apiClient.codeRun(request);
155
- const data = response.data;
156
- const charts = data.artifacts?.charts?.map(parseChart) ?? [];
157
- return {
158
- exitCode: data.exitCode ?? 0,
159
- result: data.result ?? '',
160
- artifacts: {
161
- stdout: data.result ?? '',
162
- charts,
163
- },
164
- };
165
- }
166
- /**
167
- * Creates a new long-running background session in the Sandbox.
168
- *
169
- * Sessions are background processes that maintain state between commands, making them ideal for
170
- * scenarios requiring multiple related commands or persistent environment setup. You can run
171
- * long-running commands and monitor process status.
172
- *
173
- * @param {string} sessionId - Unique identifier for the new session
174
- * @returns {Promise<void>}
175
- *
176
- * @example
177
- * // Create a new session
178
- * const sessionId = 'my-session';
179
- * await process.createSession(sessionId);
180
- * const session = await process.getSession(sessionId);
181
- * // Do work...
182
- * await process.deleteSession(sessionId);
183
- */
184
- async createSession(sessionId) {
185
- await this.apiClient.createSession({
186
- sessionId,
187
- });
188
- }
189
- /**
190
- * Get a session in the sandbox.
191
- *
192
- * @param {string} sessionId - Unique identifier of the session to retrieve
193
- * @returns {Promise<Session>} Session information including:
194
- * - sessionId: The session's unique identifier
195
- * - commands: List of commands executed in the session
196
- *
197
- * @example
198
- * const session = await process.getSession('my-session');
199
- * session.commands.forEach(cmd => {
200
- * console.log(`Command: ${cmd.command}`);
201
- * });
202
- */
203
- async getSession(sessionId) {
204
- const response = await this.apiClient.getSession(sessionId);
205
- return response.data;
206
- }
207
- /**
208
- * Get the sandbox entrypoint session
209
- *
210
- * @returns {Promise<Session>} Entrypoint session information including:
211
- * - sessionId: The entrypoint session's unique identifier
212
- * - commands: List of commands executed in the entrypoint session
213
- *
214
- * @example
215
- * const session = await process.getEntrypointSession();
216
- * session.commands.forEach(cmd => {
217
- * console.log(`Command: ${cmd.command}`);
218
- * });
219
- */
220
- async getEntrypointSession() {
221
- const response = await this.apiClient.getEntrypointSession();
222
- return response.data;
223
- }
224
- /**
225
- * Gets information about a specific command executed in a session.
226
- *
227
- * @param {string} sessionId - Unique identifier of the session
228
- * @param {string} commandId - Unique identifier of the command
229
- * @returns {Promise<Command>} Command information including:
230
- * - id: The command's unique identifier
231
- * - command: The executed command string
232
- * - exitCode: Command's exit status (if completed)
233
- *
234
- * @example
235
- * const cmd = await process.getSessionCommand('my-session', 'cmd-123');
236
- * if (cmd.exitCode === 0) {
237
- * console.log(`Command ${cmd.command} completed successfully`);
238
- * }
239
- */
240
- async getSessionCommand(sessionId, commandId) {
241
- const response = await this.apiClient.getSessionCommand(sessionId, commandId);
242
- return response.data;
243
- }
244
- /**
245
- * Executes a command in an existing session.
246
- *
247
- * @param {string} sessionId - Unique identifier of the session to use
248
- * @param {SessionExecuteRequest} req - Command execution request containing:
249
- * - command: The command to execute
250
- * - runAsync: Whether to execute asynchronously
251
- * - suppressInputEcho: Whether to suppress input echo. Default is `false`.
252
- * @param {number} timeout - Timeout in seconds
253
- * @returns {Promise<SessionExecuteResponse>} Command execution results containing:
254
- * - cmdId: Unique identifier for the executed command
255
- * - output: Combined command output (stdout and stderr) (if synchronous execution)
256
- * - stdout: Standard output from the command
257
- * - stderr: Standard error from the command
258
- * - exitCode: Command exit status (if synchronous execution)
259
- *
260
- * @example
261
- * // Execute commands in sequence, maintaining state
262
- * const sessionId = 'my-session';
263
- *
264
- * // Change directory
265
- * await process.executeSessionCommand(sessionId, {
266
- * command: 'cd /home/daytona'
267
- * });
268
- *
269
- * // Run command in new directory
270
- * const result = await process.executeSessionCommand(sessionId, {
271
- * command: 'pwd'
272
- * });
273
- * console.log('[STDOUT]:', result.stdout);
274
- * console.log('[STDERR]:', result.stderr);
275
- */
276
- async executeSessionCommand(sessionId, req, timeout) {
277
- const response = await this.apiClient.sessionExecuteCommand(sessionId, req, timeout ? { timeout: timeout * 1000 } : {});
278
- return {
279
- ...response.data,
280
- stdout: response.data.stdout ?? '',
281
- stderr: response.data.stderr ?? '',
282
- };
283
- }
284
- async getSessionCommandLogs(sessionId, commandId, onStdout, onStderr) {
285
- if (!onStdout && !onStderr) {
286
- const response = await this.apiClient.getSessionCommandLogs(sessionId, commandId);
85
+ clientConfig = __runInitializers(this, _instanceExtraInitializers);
86
+ apiClient;
87
+ getPreviewToken;
88
+ language;
89
+ constructor(clientConfig, apiClient, getPreviewToken, language) {
90
+ this.clientConfig = clientConfig;
91
+ this.apiClient = apiClient;
92
+ this.getPreviewToken = getPreviewToken;
93
+ this.language = language;
94
+ }
95
+ /**
96
+ * Executes a shell command in the Sandbox.
97
+ *
98
+ * @param {string} command - Shell command to execute
99
+ * @param {string} [cwd] - Working directory for command execution. If not specified, uses the sandbox working directory.
100
+ * @param {Record<string, string>} [env] - Environment variables to set for the command
101
+ * @param {number} [timeout] - Maximum time in seconds to wait for the command to complete.
102
+ * @returns {Promise<ExecuteResponse>} Command execution results containing:
103
+ * - exitCode: The command's exit status
104
+ * - result: Standard output from the command
105
+ * - artifacts: ExecutionArtifacts object containing `stdout` (same as result) and `charts` (matplotlib charts metadata)
106
+ *
107
+ * @example
108
+ * // Simple command
109
+ * const response = await process.executeCommand('echo "Hello"');
110
+ * console.log(response.artifacts.stdout); // Prints: Hello
111
+ *
112
+ * @example
113
+ * // Command with working directory
114
+ * const result = await process.executeCommand('ls', 'workspace/src');
115
+ *
116
+ * @example
117
+ * // Command with timeout
118
+ * const result = await process.executeCommand('sleep 10', undefined, 5);
119
+ */
120
+ async executeCommand(command, cwd, env, timeout) {
121
+ const response = await this.apiClient.executeCommand({
122
+ command,
123
+ timeout,
124
+ cwd: cwd,
125
+ envs: env && Object.keys(env).length ? env : undefined,
126
+ });
127
+ const result = response.data.result ?? '';
287
128
  return {
288
- output: response.data.output ?? '',
289
- stdout: response.data.stdout ?? '',
290
- stderr: response.data.stderr ?? '',
129
+ exitCode: response.data.exitCode ?? response.data.code,
130
+ result,
131
+ artifacts: {
132
+ stdout: result,
133
+ },
134
+ };
135
+ }
136
+ /**
137
+ * Executes code in the Sandbox using the appropriate language runtime.
138
+ *
139
+ * @param {string} code - Code to execute
140
+ * @param {CodeRunParams} params - Parameters for code execution
141
+ * @param {number} [timeout] - Maximum time in seconds to wait for execution to complete
142
+ * @returns {Promise<ExecuteResponse>} Code execution results containing:
143
+ * - exitCode: The execution's exit status
144
+ * - result: Standard output from the code
145
+ * - artifacts: ExecutionArtifacts object containing `stdout` (same as result) and `charts` (matplotlib charts metadata)
146
+ *
147
+ * @example
148
+ * // Run TypeScript code
149
+ * const response = await process.codeRun(`
150
+ * const x = 10;
151
+ * const y = 20;
152
+ * console.log(\`Sum: \${x + y}\`);
153
+ * `);
154
+ * console.log(response.artifacts.stdout); // Prints: Sum: 30
155
+ *
156
+ * @example
157
+ * // Run Python code with matplotlib
158
+ * const response = await process.codeRun(`
159
+ * import matplotlib.pyplot as plt
160
+ * import numpy as np
161
+ *
162
+ * x = np.linspace(0, 10, 30)
163
+ * y = np.sin(x)
164
+ *
165
+ * plt.figure(figsize=(8, 5))
166
+ * plt.plot(x, y, 'b-', linewidth=2)
167
+ * plt.title('Line Chart')
168
+ * plt.xlabel('X-axis (seconds)')
169
+ * plt.ylabel('Y-axis (amplitude)')
170
+ * plt.grid(True)
171
+ * plt.show()
172
+ * `);
173
+ *
174
+ * if (response.artifacts?.charts) {
175
+ * const chart = response.artifacts.charts[0];
176
+ *
177
+ * console.log(`Type: ${chart.type}`);
178
+ * console.log(`Title: ${chart.title}`);
179
+ * if (chart.type === ChartType.LINE) {
180
+ * const lineChart = chart as LineChart
181
+ * console.log('X Label:', lineChart.x_label)
182
+ * console.log('Y Label:', lineChart.y_label)
183
+ * console.log('X Ticks:', lineChart.x_ticks)
184
+ * console.log('Y Ticks:', lineChart.y_ticks)
185
+ * console.log('X Tick Labels:', lineChart.x_tick_labels)
186
+ * console.log('Y Tick Labels:', lineChart.y_tick_labels)
187
+ * console.log('X Scale:', lineChart.x_scale)
188
+ * console.log('Y Scale:', lineChart.y_scale)
189
+ * console.log('Elements:')
190
+ * console.dir(lineChart.elements, { depth: null })
191
+ * }
192
+ * }
193
+ */
194
+ async codeRun(code, params, timeout) {
195
+ if (!this.language) {
196
+ throw new Error('Code language is required for codeRun');
197
+ }
198
+ const request = {
199
+ code,
200
+ language: this.language,
201
+ argv: params?.argv,
202
+ envs: params?.env,
203
+ timeout,
204
+ };
205
+ const response = await this.apiClient.codeRun(request);
206
+ const data = response.data;
207
+ const charts = data.artifacts?.charts?.map(parseChart) ?? [];
208
+ return {
209
+ exitCode: data.exitCode ?? 0,
210
+ result: data.result ?? '',
211
+ artifacts: {
212
+ stdout: data.result ?? '',
213
+ charts,
214
+ },
291
215
  };
292
216
  }
293
- const url = `${this.clientConfig.basePath.replace(/^http/, 'ws')}/process/session/${sessionId}/command/${commandId}/logs?follow=true`;
294
- const ws = await createSandboxWebSocket(url, this.clientConfig.baseOptions?.headers || {}, this.getPreviewToken);
295
- await stdDemuxStream(ws, onStdout, onStderr);
296
- }
297
- async getEntrypointLogs(onStdout, onStderr) {
298
- if (!onStdout && !onStderr) {
299
- const response = await this.apiClient.getEntrypointLogs();
217
+ /**
218
+ * Creates a new long-running background session in the Sandbox.
219
+ *
220
+ * Sessions are background processes that maintain state between commands, making them ideal for
221
+ * scenarios requiring multiple related commands or persistent environment setup. You can run
222
+ * long-running commands and monitor process status.
223
+ *
224
+ * @param {string} sessionId - Unique identifier for the new session
225
+ * @returns {Promise<void>}
226
+ *
227
+ * @example
228
+ * // Create a new session
229
+ * const sessionId = 'my-session';
230
+ * await process.createSession(sessionId);
231
+ * const session = await process.getSession(sessionId);
232
+ * // Do work...
233
+ * await process.deleteSession(sessionId);
234
+ */
235
+ async createSession(sessionId) {
236
+ await this.apiClient.createSession({
237
+ sessionId,
238
+ });
239
+ }
240
+ /**
241
+ * Get a session in the sandbox.
242
+ *
243
+ * @param {string} sessionId - Unique identifier of the session to retrieve
244
+ * @returns {Promise<Session>} Session information including:
245
+ * - sessionId: The session's unique identifier
246
+ * - commands: List of commands executed in the session
247
+ *
248
+ * @example
249
+ * const session = await process.getSession('my-session');
250
+ * session.commands.forEach(cmd => {
251
+ * console.log(`Command: ${cmd.command}`);
252
+ * });
253
+ */
254
+ async getSession(sessionId) {
255
+ const response = await this.apiClient.getSession(sessionId);
256
+ return response.data;
257
+ }
258
+ /**
259
+ * Get the sandbox entrypoint session
260
+ *
261
+ * @returns {Promise<Session>} Entrypoint session information including:
262
+ * - sessionId: The entrypoint session's unique identifier
263
+ * - commands: List of commands executed in the entrypoint session
264
+ *
265
+ * @example
266
+ * const session = await process.getEntrypointSession();
267
+ * session.commands.forEach(cmd => {
268
+ * console.log(`Command: ${cmd.command}`);
269
+ * });
270
+ */
271
+ async getEntrypointSession() {
272
+ const response = await this.apiClient.getEntrypointSession();
273
+ return response.data;
274
+ }
275
+ /**
276
+ * Gets information about a specific command executed in a session.
277
+ *
278
+ * @param {string} sessionId - Unique identifier of the session
279
+ * @param {string} commandId - Unique identifier of the command
280
+ * @returns {Promise<Command>} Command information including:
281
+ * - id: The command's unique identifier
282
+ * - command: The executed command string
283
+ * - exitCode: Command's exit status (if completed)
284
+ *
285
+ * @example
286
+ * const cmd = await process.getSessionCommand('my-session', 'cmd-123');
287
+ * if (cmd.exitCode === 0) {
288
+ * console.log(`Command ${cmd.command} completed successfully`);
289
+ * }
290
+ */
291
+ async getSessionCommand(sessionId, commandId) {
292
+ const response = await this.apiClient.getSessionCommand(sessionId, commandId);
293
+ return response.data;
294
+ }
295
+ /**
296
+ * Executes a command in an existing session.
297
+ *
298
+ * @param {string} sessionId - Unique identifier of the session to use
299
+ * @param {SessionExecuteRequest} req - Command execution request containing:
300
+ * - command: The command to execute
301
+ * - runAsync: Whether to execute asynchronously
302
+ * - suppressInputEcho: Whether to suppress input echo. Default is `false`.
303
+ * @param {number} timeout - Timeout in seconds
304
+ * @returns {Promise<SessionExecuteResponse>} Command execution results containing:
305
+ * - cmdId: Unique identifier for the executed command
306
+ * - output: Combined command output (stdout and stderr) (if synchronous execution)
307
+ * - stdout: Standard output from the command
308
+ * - stderr: Standard error from the command
309
+ * - exitCode: Command exit status (if synchronous execution)
310
+ *
311
+ * @example
312
+ * // Execute commands in sequence, maintaining state
313
+ * const sessionId = 'my-session';
314
+ *
315
+ * // Change directory
316
+ * await process.executeSessionCommand(sessionId, {
317
+ * command: 'cd /home/daytona'
318
+ * });
319
+ *
320
+ * // Run command in new directory
321
+ * const result = await process.executeSessionCommand(sessionId, {
322
+ * command: 'pwd'
323
+ * });
324
+ * console.log('[STDOUT]:', result.stdout);
325
+ * console.log('[STDERR]:', result.stderr);
326
+ */
327
+ async executeSessionCommand(sessionId, req, timeout) {
328
+ const response = await this.apiClient.sessionExecuteCommand(sessionId, req, timeout ? { timeout: timeout * 1000 } : {});
300
329
  return {
301
- output: response.data.output ?? '',
330
+ ...response.data,
302
331
  stdout: response.data.stdout ?? '',
303
332
  stderr: response.data.stderr ?? '',
304
333
  };
305
334
  }
306
- const url = `${this.clientConfig.basePath.replace(/^http/, 'ws')}/process/session/entrypoint/logs?follow=true`;
307
- const ws = await createSandboxWebSocket(url, this.clientConfig.baseOptions?.headers || {}, this.getPreviewToken);
308
- await stdDemuxStream(ws, onStdout, onStderr);
309
- }
310
- /**
311
- * Sends input data to a command executed in a session.
312
- *
313
- * @param {string} sessionId - Unique identifier of the session
314
- * @param {string} commandId - Unique identifier of the command
315
- * @param {string} data - Input data to send
316
- * @returns {Promise<void>}
317
- */
318
- async sendSessionCommandInput(sessionId, commandId, data) {
319
- await this.apiClient.sendInput(sessionId, commandId, { data });
320
- }
321
- /**
322
- * Lists all active sessions in the Sandbox.
323
- *
324
- * @returns {Promise<Session[]>} Array of active sessions
325
- *
326
- * @example
327
- * const sessions = await process.listSessions();
328
- * sessions.forEach(session => {
329
- * console.log(`Session ${session.sessionId}:`);
330
- * session.commands.forEach(cmd => {
331
- * console.log(`- ${cmd.command} (${cmd.exitCode})`);
332
- * });
333
- * });
334
- */
335
- async listSessions() {
336
- const response = await this.apiClient.listSessions();
337
- return response.data;
338
- }
339
- /**
340
- * Delete a session from the Sandbox.
341
- *
342
- * @param {string} sessionId - Unique identifier of the session to delete
343
- * @returns {Promise<void>}
344
- *
345
- * @example
346
- * // Clean up a completed session
347
- * await process.deleteSession('my-session');
348
- */
349
- async deleteSession(sessionId) {
350
- await this.apiClient.deleteSession(sessionId);
351
- }
352
- /**
353
- * Create a new PTY (pseudo-terminal) session in the sandbox.
354
- *
355
- * Creates an interactive terminal session that can execute commands and handle user input.
356
- * The PTY session behaves like a real terminal, supporting features like command history.
357
- *
358
- * @param {PtyCreateOptions & PtyConnectOptions} options - PTY session configuration including creation and connection options
359
- * @returns {Promise<PtyHandle>} PTY handle for managing the session
360
- *
361
- * @example
362
- * // Create a PTY session with custom configuration
363
- * const ptyHandle = await process.createPty({
364
- * id: 'my-interactive-session',
365
- * cwd: '/workspace',
366
- * envs: { TERM: 'xterm-256color', LANG: 'en_US.UTF-8' },
367
- * cols: 120,
368
- * rows: 30,
369
- * onData: (data) => {
370
- * // Handle terminal output
371
- * const text = new TextDecoder().decode(data);
372
- * process.stdout.write(text);
373
- * },
374
- * });
375
- *
376
- * // Wait for connection to be established
377
- * await ptyHandle.waitForConnection();
378
- *
379
- * // Send commands to the terminal
380
- * await ptyHandle.sendInput('ls -la\n');
381
- * await ptyHandle.sendInput('echo "Hello, PTY!"\n');
382
- * await ptyHandle.sendInput('exit\n');
383
- *
384
- * // Wait for completion and get result
385
- * const result = await ptyHandle.wait();
386
- * console.log(`PTY session completed with exit code: ${result.exitCode}`);
387
- *
388
- * // Clean up
389
- * await ptyHandle.disconnect();
390
- */
391
- async createPty(options) {
392
- const request = {
393
- id: options.id,
394
- cwd: options.cwd,
395
- envs: options.envs,
396
- cols: options.cols,
397
- rows: options.rows,
398
- lazyStart: true,
399
- };
400
- const response = await this.apiClient.createPtySession(request);
401
- return await this.connectPty(response.data.sessionId, options);
402
- }
403
- /**
404
- * Connect to an existing PTY session in the sandbox.
405
- *
406
- * Establishes a WebSocket connection to an existing PTY session, allowing you to
407
- * interact with a previously created terminal session.
408
- *
409
- * @param {string} sessionId - ID of the PTY session to connect to
410
- * @param {PtyConnectOptions} options - Options for the connection including data handler
411
- * @returns {Promise<PtyHandle>} PTY handle for managing the session
412
- *
413
- * @example
414
- * // Connect to an existing PTY session
415
- * const handle = await process.connectPty('my-session', {
416
- * onData: (data) => {
417
- * // Handle terminal output
418
- * const text = new TextDecoder().decode(data);
419
- * process.stdout.write(text);
420
- * },
421
- * });
422
- *
423
- * // Wait for connection to be established
424
- * await handle.waitForConnection();
425
- *
426
- * // Send commands to the existing session
427
- * await handle.sendInput('pwd\n');
428
- * await handle.sendInput('ls -la\n');
429
- * await handle.sendInput('exit\n');
430
- *
431
- * // Wait for completion
432
- * const result = await handle.wait();
433
- * console.log(`Session exited with code: ${result.exitCode}`);
434
- *
435
- * // Clean up
436
- * await handle.disconnect();
437
- */
438
- async connectPty(sessionId, options) {
439
- const url = `${this.clientConfig.basePath.replace(/^http/, 'ws')}/process/pty/${sessionId}/connect`;
440
- const ws = await createSandboxWebSocket(url, this.clientConfig.baseOptions?.headers || {}, this.getPreviewToken);
441
- const handle = new PtyHandle(ws, (cols, rows) => this.resizePtySession(sessionId, cols, rows), () => this.killPtySession(sessionId), options.onData, sessionId);
442
- await handle.waitForConnection();
443
- return handle;
444
- }
445
- /**
446
- * List all PTY sessions in the sandbox.
447
- *
448
- * Retrieves information about all PTY sessions, both active and inactive,
449
- * that have been created in this sandbox.
450
- *
451
- * @returns {Promise<PtySessionInfo[]>} Array of PTY session information
452
- *
453
- * @example
454
- * // List all PTY sessions
455
- * const sessions = await process.listPtySessions();
456
- *
457
- * for (const session of sessions) {
458
- * console.log(`Session ID: ${session.id}`);
459
- * console.log(`Active: ${session.active}`);
460
- * console.log(`Created: ${session.createdAt}`);
461
- * }
462
- * console.log('---');
463
- * }
464
- */
465
- async listPtySessions() {
466
- return (await this.apiClient.listPtySessions()).data.sessions;
467
- }
468
- /**
469
- * Get detailed information about a specific PTY session.
470
- *
471
- * Retrieves comprehensive information about a PTY session including its current state,
472
- * configuration, and metadata.
473
- *
474
- * @param {string} sessionId - ID of the PTY session to retrieve information for
475
- * @returns {Promise<PtySessionInfo>} PTY session information
476
- *
477
- * @throws {Error} If the PTY session doesn't exist
478
- *
479
- * @example
480
- * // Get details about a specific PTY session
481
- * const session = await process.getPtySessionInfo('my-session');
482
- *
483
- * console.log(`Session ID: ${session.id}`);
484
- * console.log(`Active: ${session.active}`);
485
- * console.log(`Working Directory: ${session.cwd}`);
486
- * console.log(`Terminal Size: ${session.cols}x${session.rows}`);
487
- *
488
- * if (session.processId) {
489
- * console.log(`Process ID: ${session.processId}`);
490
- * }
491
- */
492
- async getPtySessionInfo(sessionId) {
493
- return (await this.apiClient.getPtySession(sessionId)).data;
494
- }
495
- /**
496
- * Kill a PTY session and terminate its associated process.
497
- *
498
- * Forcefully terminates the PTY session and cleans up all associated resources.
499
- * This will close any active connections and kill the underlying shell process.
500
- *
501
- * @param {string} sessionId - ID of the PTY session to kill
502
- * @returns {Promise<void>}
503
- *
504
- * @throws {Error} If the PTY session doesn't exist or cannot be killed
505
- *
506
- * @note This operation is irreversible. Any unsaved work in the terminal session will be lost.
507
- *
508
- * @example
509
- * // Kill a specific PTY session
510
- * await process.killPtySession('my-session');
511
- *
512
- * // Verify the session is no longer active
513
- * try {
514
- * const info = await process.getPtySessionInfo('my-session');
515
- * console.log(`Session still exists but active: ${info.active}`);
516
- * } catch (error) {
517
- * console.log('Session has been completely removed');
518
- * }
519
- */
520
- async killPtySession(sessionId) {
521
- await this.apiClient.deletePtySession(sessionId);
522
- }
523
- /**
524
- * Resize a PTY session's terminal dimensions.
525
- *
526
- * Changes the terminal size of an active PTY session. This is useful when the
527
- * client terminal is resized or when you need to adjust the display for different
528
- * output requirements.
529
- *
530
- * @param {string} sessionId - ID of the PTY session to resize
531
- * @param {number} cols - New number of terminal columns
532
- * @param {number} rows - New number of terminal rows
533
- * @returns {Promise<PtySessionInfo>} Updated session information reflecting the new terminal size
534
- *
535
- * @throws {Error} If the PTY session doesn't exist or resize operation fails
536
- *
537
- * @note The resize operation will send a SIGWINCH signal to the shell process,
538
- * allowing terminal applications to adapt to the new size.
539
- *
540
- * @example
541
- * // Resize a PTY session to a larger terminal
542
- * const updatedInfo = await process.resizePtySession('my-session', 150, 40);
543
- * console.log(`Terminal resized to ${updatedInfo.cols}x${updatedInfo.rows}`);
544
- *
545
- * // You can also use the PtyHandle's resize method
546
- * await ptyHandle.resize(150, 40); // cols, rows
547
- */
548
- async resizePtySession(sessionId, cols, rows) {
549
- return (await this.apiClient.resizePtySession(sessionId, { cols, rows })).data;
550
- }
551
- }
552
- __decorate([
553
- WithInstrumentation(),
554
- __metadata("design:type", Function),
555
- __metadata("design:paramtypes", [String, String, Object, Number]),
556
- __metadata("design:returntype", Promise)
557
- ], Process.prototype, "executeCommand", null);
558
- __decorate([
559
- WithInstrumentation(),
560
- __metadata("design:type", Function),
561
- __metadata("design:paramtypes", [String, CodeRunParams, Number]),
562
- __metadata("design:returntype", Promise)
563
- ], Process.prototype, "codeRun", null);
564
- __decorate([
565
- WithInstrumentation(),
566
- __metadata("design:type", Function),
567
- __metadata("design:paramtypes", [String]),
568
- __metadata("design:returntype", Promise)
569
- ], Process.prototype, "createSession", null);
570
- __decorate([
571
- WithInstrumentation(),
572
- __metadata("design:type", Function),
573
- __metadata("design:paramtypes", [String, String]),
574
- __metadata("design:returntype", Promise)
575
- ], Process.prototype, "getSessionCommand", null);
576
- __decorate([
577
- WithInstrumentation(),
578
- __metadata("design:type", Function),
579
- __metadata("design:paramtypes", [String, Object, Number]),
580
- __metadata("design:returntype", Promise)
581
- ], Process.prototype, "executeSessionCommand", null);
582
- __decorate([
583
- WithInstrumentation(),
584
- __metadata("design:type", Function),
585
- __metadata("design:paramtypes", [String, String, Function, Function]),
586
- __metadata("design:returntype", Promise)
587
- ], Process.prototype, "getSessionCommandLogs", null);
588
- __decorate([
589
- WithInstrumentation(),
590
- __metadata("design:type", Function),
591
- __metadata("design:paramtypes", [Function, Function]),
592
- __metadata("design:returntype", Promise)
593
- ], Process.prototype, "getEntrypointLogs", null);
594
- __decorate([
595
- WithInstrumentation(),
596
- __metadata("design:type", Function),
597
- __metadata("design:paramtypes", []),
598
- __metadata("design:returntype", Promise)
599
- ], Process.prototype, "listSessions", null);
600
- __decorate([
601
- WithInstrumentation(),
602
- __metadata("design:type", Function),
603
- __metadata("design:paramtypes", [String]),
604
- __metadata("design:returntype", Promise)
605
- ], Process.prototype, "deleteSession", null);
606
- __decorate([
607
- WithInstrumentation(),
608
- __metadata("design:type", Function),
609
- __metadata("design:paramtypes", [Object]),
610
- __metadata("design:returntype", Promise)
611
- ], Process.prototype, "createPty", null);
612
- __decorate([
613
- WithInstrumentation(),
614
- __metadata("design:type", Function),
615
- __metadata("design:paramtypes", [String, Object]),
616
- __metadata("design:returntype", Promise)
617
- ], Process.prototype, "connectPty", null);
618
- __decorate([
619
- WithInstrumentation(),
620
- __metadata("design:type", Function),
621
- __metadata("design:paramtypes", []),
622
- __metadata("design:returntype", Promise)
623
- ], Process.prototype, "listPtySessions", null);
624
- __decorate([
625
- WithInstrumentation(),
626
- __metadata("design:type", Function),
627
- __metadata("design:paramtypes", [String]),
628
- __metadata("design:returntype", Promise)
629
- ], Process.prototype, "getPtySessionInfo", null);
630
- __decorate([
631
- WithInstrumentation(),
632
- __metadata("design:type", Function),
633
- __metadata("design:paramtypes", [String]),
634
- __metadata("design:returntype", Promise)
635
- ], Process.prototype, "killPtySession", null);
636
- __decorate([
637
- WithInstrumentation(),
638
- __metadata("design:type", Function),
639
- __metadata("design:paramtypes", [String, Number, Number]),
640
- __metadata("design:returntype", Promise)
641
- ], Process.prototype, "resizePtySession", null);
335
+ async getSessionCommandLogs(sessionId, commandId, onStdout, onStderr) {
336
+ if (!onStdout && !onStderr) {
337
+ const response = await this.apiClient.getSessionCommandLogs(sessionId, commandId);
338
+ return {
339
+ output: response.data.output ?? '',
340
+ stdout: response.data.stdout ?? '',
341
+ stderr: response.data.stderr ?? '',
342
+ };
343
+ }
344
+ const url = `${this.clientConfig.basePath.replace(/^http/, 'ws')}/process/session/${sessionId}/command/${commandId}/logs?follow=true`;
345
+ const ws = await createSandboxWebSocket(url, this.clientConfig.baseOptions?.headers || {}, this.getPreviewToken);
346
+ await stdDemuxStream(ws, onStdout, onStderr);
347
+ }
348
+ async getEntrypointLogs(onStdout, onStderr) {
349
+ if (!onStdout && !onStderr) {
350
+ const response = await this.apiClient.getEntrypointLogs();
351
+ return {
352
+ output: response.data.output ?? '',
353
+ stdout: response.data.stdout ?? '',
354
+ stderr: response.data.stderr ?? '',
355
+ };
356
+ }
357
+ const url = `${this.clientConfig.basePath.replace(/^http/, 'ws')}/process/session/entrypoint/logs?follow=true`;
358
+ const ws = await createSandboxWebSocket(url, this.clientConfig.baseOptions?.headers || {}, this.getPreviewToken);
359
+ await stdDemuxStream(ws, onStdout, onStderr);
360
+ }
361
+ /**
362
+ * Sends input data to a command executed in a session.
363
+ *
364
+ * @param {string} sessionId - Unique identifier of the session
365
+ * @param {string} commandId - Unique identifier of the command
366
+ * @param {string} data - Input data to send
367
+ * @returns {Promise<void>}
368
+ */
369
+ async sendSessionCommandInput(sessionId, commandId, data) {
370
+ await this.apiClient.sendInput(sessionId, commandId, { data });
371
+ }
372
+ /**
373
+ * Lists all active sessions in the Sandbox.
374
+ *
375
+ * @returns {Promise<Session[]>} Array of active sessions
376
+ *
377
+ * @example
378
+ * const sessions = await process.listSessions();
379
+ * sessions.forEach(session => {
380
+ * console.log(`Session ${session.sessionId}:`);
381
+ * session.commands.forEach(cmd => {
382
+ * console.log(`- ${cmd.command} (${cmd.exitCode})`);
383
+ * });
384
+ * });
385
+ */
386
+ async listSessions() {
387
+ const response = await this.apiClient.listSessions();
388
+ return response.data;
389
+ }
390
+ /**
391
+ * Delete a session from the Sandbox.
392
+ *
393
+ * @param {string} sessionId - Unique identifier of the session to delete
394
+ * @returns {Promise<void>}
395
+ *
396
+ * @example
397
+ * // Clean up a completed session
398
+ * await process.deleteSession('my-session');
399
+ */
400
+ async deleteSession(sessionId) {
401
+ await this.apiClient.deleteSession(sessionId);
402
+ }
403
+ /**
404
+ * Create a new PTY (pseudo-terminal) session in the sandbox.
405
+ *
406
+ * Creates an interactive terminal session that can execute commands and handle user input.
407
+ * The PTY session behaves like a real terminal, supporting features like command history.
408
+ *
409
+ * @param {PtyCreateOptions & PtyConnectOptions} options - PTY session configuration including creation and connection options
410
+ * @returns {Promise<PtyHandle>} PTY handle for managing the session
411
+ *
412
+ * @example
413
+ * // Create a PTY session with custom configuration
414
+ * const ptyHandle = await process.createPty({
415
+ * id: 'my-interactive-session',
416
+ * cwd: '/workspace',
417
+ * envs: { TERM: 'xterm-256color', LANG: 'en_US.UTF-8' },
418
+ * cols: 120,
419
+ * rows: 30,
420
+ * onData: (data) => {
421
+ * // Handle terminal output
422
+ * const text = new TextDecoder().decode(data);
423
+ * process.stdout.write(text);
424
+ * },
425
+ * });
426
+ *
427
+ * // Wait for connection to be established
428
+ * await ptyHandle.waitForConnection();
429
+ *
430
+ * // Send commands to the terminal
431
+ * await ptyHandle.sendInput('ls -la\n');
432
+ * await ptyHandle.sendInput('echo "Hello, PTY!"\n');
433
+ * await ptyHandle.sendInput('exit\n');
434
+ *
435
+ * // Wait for completion and get result
436
+ * const result = await ptyHandle.wait();
437
+ * console.log(`PTY session completed with exit code: ${result.exitCode}`);
438
+ *
439
+ * // Clean up
440
+ * await ptyHandle.disconnect();
441
+ */
442
+ async createPty(options) {
443
+ const request = {
444
+ id: options.id,
445
+ cwd: options.cwd,
446
+ envs: options.envs,
447
+ cols: options.cols,
448
+ rows: options.rows,
449
+ lazyStart: true,
450
+ };
451
+ const response = await this.apiClient.createPtySession(request);
452
+ return await this.connectPty(response.data.sessionId, options);
453
+ }
454
+ /**
455
+ * Connect to an existing PTY session in the sandbox.
456
+ *
457
+ * Establishes a WebSocket connection to an existing PTY session, allowing you to
458
+ * interact with a previously created terminal session.
459
+ *
460
+ * @param {string} sessionId - ID of the PTY session to connect to
461
+ * @param {PtyConnectOptions} options - Options for the connection including data handler
462
+ * @returns {Promise<PtyHandle>} PTY handle for managing the session
463
+ *
464
+ * @example
465
+ * // Connect to an existing PTY session
466
+ * const handle = await process.connectPty('my-session', {
467
+ * onData: (data) => {
468
+ * // Handle terminal output
469
+ * const text = new TextDecoder().decode(data);
470
+ * process.stdout.write(text);
471
+ * },
472
+ * });
473
+ *
474
+ * // Wait for connection to be established
475
+ * await handle.waitForConnection();
476
+ *
477
+ * // Send commands to the existing session
478
+ * await handle.sendInput('pwd\n');
479
+ * await handle.sendInput('ls -la\n');
480
+ * await handle.sendInput('exit\n');
481
+ *
482
+ * // Wait for completion
483
+ * const result = await handle.wait();
484
+ * console.log(`Session exited with code: ${result.exitCode}`);
485
+ *
486
+ * // Clean up
487
+ * await handle.disconnect();
488
+ */
489
+ async connectPty(sessionId, options) {
490
+ const url = `${this.clientConfig.basePath.replace(/^http/, 'ws')}/process/pty/${sessionId}/connect`;
491
+ const ws = await createSandboxWebSocket(url, this.clientConfig.baseOptions?.headers || {}, this.getPreviewToken);
492
+ const handle = new PtyHandle(ws, (cols, rows) => this.resizePtySession(sessionId, cols, rows), () => this.killPtySession(sessionId), options.onData, sessionId);
493
+ await handle.waitForConnection();
494
+ return handle;
495
+ }
496
+ /**
497
+ * List all PTY sessions in the sandbox.
498
+ *
499
+ * Retrieves information about all PTY sessions, both active and inactive,
500
+ * that have been created in this sandbox.
501
+ *
502
+ * @returns {Promise<PtySessionInfo[]>} Array of PTY session information
503
+ *
504
+ * @example
505
+ * // List all PTY sessions
506
+ * const sessions = await process.listPtySessions();
507
+ *
508
+ * for (const session of sessions) {
509
+ * console.log(`Session ID: ${session.id}`);
510
+ * console.log(`Active: ${session.active}`);
511
+ * console.log(`Created: ${session.createdAt}`);
512
+ * }
513
+ * console.log('---');
514
+ * }
515
+ */
516
+ async listPtySessions() {
517
+ return (await this.apiClient.listPtySessions()).data.sessions;
518
+ }
519
+ /**
520
+ * Get detailed information about a specific PTY session.
521
+ *
522
+ * Retrieves comprehensive information about a PTY session including its current state,
523
+ * configuration, and metadata.
524
+ *
525
+ * @param {string} sessionId - ID of the PTY session to retrieve information for
526
+ * @returns {Promise<PtySessionInfo>} PTY session information
527
+ *
528
+ * @throws {Error} If the PTY session doesn't exist
529
+ *
530
+ * @example
531
+ * // Get details about a specific PTY session
532
+ * const session = await process.getPtySessionInfo('my-session');
533
+ *
534
+ * console.log(`Session ID: ${session.id}`);
535
+ * console.log(`Active: ${session.active}`);
536
+ * console.log(`Working Directory: ${session.cwd}`);
537
+ * console.log(`Terminal Size: ${session.cols}x${session.rows}`);
538
+ *
539
+ * if (session.processId) {
540
+ * console.log(`Process ID: ${session.processId}`);
541
+ * }
542
+ */
543
+ async getPtySessionInfo(sessionId) {
544
+ return (await this.apiClient.getPtySession(sessionId)).data;
545
+ }
546
+ /**
547
+ * Kill a PTY session and terminate its associated process.
548
+ *
549
+ * Forcefully terminates the PTY session and cleans up all associated resources.
550
+ * This will close any active connections and kill the underlying shell process.
551
+ *
552
+ * @param {string} sessionId - ID of the PTY session to kill
553
+ * @returns {Promise<void>}
554
+ *
555
+ * @throws {Error} If the PTY session doesn't exist or cannot be killed
556
+ *
557
+ * @note This operation is irreversible. Any unsaved work in the terminal session will be lost.
558
+ *
559
+ * @example
560
+ * // Kill a specific PTY session
561
+ * await process.killPtySession('my-session');
562
+ *
563
+ * // Verify the session is no longer active
564
+ * try {
565
+ * const info = await process.getPtySessionInfo('my-session');
566
+ * console.log(`Session still exists but active: ${info.active}`);
567
+ * } catch (error) {
568
+ * console.log('Session has been completely removed');
569
+ * }
570
+ */
571
+ async killPtySession(sessionId) {
572
+ await this.apiClient.deletePtySession(sessionId);
573
+ }
574
+ /**
575
+ * Resize a PTY session's terminal dimensions.
576
+ *
577
+ * Changes the terminal size of an active PTY session. This is useful when the
578
+ * client terminal is resized or when you need to adjust the display for different
579
+ * output requirements.
580
+ *
581
+ * @param {string} sessionId - ID of the PTY session to resize
582
+ * @param {number} cols - New number of terminal columns
583
+ * @param {number} rows - New number of terminal rows
584
+ * @returns {Promise<PtySessionInfo>} Updated session information reflecting the new terminal size
585
+ *
586
+ * @throws {Error} If the PTY session doesn't exist or resize operation fails
587
+ *
588
+ * @note The resize operation will send a SIGWINCH signal to the shell process,
589
+ * allowing terminal applications to adapt to the new size.
590
+ *
591
+ * @example
592
+ * // Resize a PTY session to a larger terminal
593
+ * const updatedInfo = await process.resizePtySession('my-session', 150, 40);
594
+ * console.log(`Terminal resized to ${updatedInfo.cols}x${updatedInfo.rows}`);
595
+ *
596
+ * // You can also use the PtyHandle's resize method
597
+ * await ptyHandle.resize(150, 40); // cols, rows
598
+ */
599
+ async resizePtySession(sessionId, cols, rows) {
600
+ return (await this.apiClient.resizePtySession(sessionId, { cols, rows })).data;
601
+ }
602
+ };
603
+ })();
604
+ export { Process };
642
605
  //# sourceMappingURL=Process.js.map