@daytona/sdk 0.161.0-alpha.1

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 (95) hide show
  1. package/README.md +180 -0
  2. package/package.json +56 -0
  3. package/src/CodeInterpreter.d.ts +94 -0
  4. package/src/CodeInterpreter.js +297 -0
  5. package/src/CodeInterpreter.js.map +1 -0
  6. package/src/ComputerUse.d.ts +538 -0
  7. package/src/ComputerUse.js +808 -0
  8. package/src/ComputerUse.js.map +1 -0
  9. package/src/Daytona.d.ts +340 -0
  10. package/src/Daytona.js +538 -0
  11. package/src/Daytona.js.map +1 -0
  12. package/src/FileSystem.d.ts +326 -0
  13. package/src/FileSystem.js +412 -0
  14. package/src/FileSystem.js.map +1 -0
  15. package/src/Git.d.ts +202 -0
  16. package/src/Git.js +326 -0
  17. package/src/Git.js.map +1 -0
  18. package/src/Image.d.ts +264 -0
  19. package/src/Image.js +546 -0
  20. package/src/Image.js.map +1 -0
  21. package/src/LspServer.d.ts +171 -0
  22. package/src/LspServer.js +258 -0
  23. package/src/LspServer.js.map +1 -0
  24. package/src/ObjectStorage.d.ts +78 -0
  25. package/src/ObjectStorage.js +199 -0
  26. package/src/ObjectStorage.js.map +1 -0
  27. package/src/Process.d.ts +490 -0
  28. package/src/Process.js +790 -0
  29. package/src/Process.js.map +1 -0
  30. package/src/PtyHandle.d.ts +154 -0
  31. package/src/PtyHandle.js +416 -0
  32. package/src/PtyHandle.js.map +1 -0
  33. package/src/Sandbox.d.ts +425 -0
  34. package/src/Sandbox.js +776 -0
  35. package/src/Sandbox.js.map +1 -0
  36. package/src/Snapshot.d.ts +139 -0
  37. package/src/Snapshot.js +248 -0
  38. package/src/Snapshot.js.map +1 -0
  39. package/src/Volume.d.ts +83 -0
  40. package/src/Volume.js +119 -0
  41. package/src/Volume.js.map +1 -0
  42. package/src/code-toolbox/SandboxJsCodeToolbox.d.ts +5 -0
  43. package/src/code-toolbox/SandboxJsCodeToolbox.js +20 -0
  44. package/src/code-toolbox/SandboxJsCodeToolbox.js.map +1 -0
  45. package/src/code-toolbox/SandboxPythonCodeToolbox.d.ts +11 -0
  46. package/src/code-toolbox/SandboxPythonCodeToolbox.js +359 -0
  47. package/src/code-toolbox/SandboxPythonCodeToolbox.js.map +1 -0
  48. package/src/code-toolbox/SandboxTsCodeToolbox.d.ts +5 -0
  49. package/src/code-toolbox/SandboxTsCodeToolbox.js +29 -0
  50. package/src/code-toolbox/SandboxTsCodeToolbox.js.map +1 -0
  51. package/src/errors/DaytonaError.d.ts +31 -0
  52. package/src/errors/DaytonaError.js +51 -0
  53. package/src/errors/DaytonaError.js.map +1 -0
  54. package/src/index.d.ts +21 -0
  55. package/src/index.js +45 -0
  56. package/src/index.js.map +1 -0
  57. package/src/types/Charts.d.ts +151 -0
  58. package/src/types/Charts.js +46 -0
  59. package/src/types/Charts.js.map +1 -0
  60. package/src/types/CodeInterpreter.d.ts +76 -0
  61. package/src/types/CodeInterpreter.js +7 -0
  62. package/src/types/CodeInterpreter.js.map +1 -0
  63. package/src/types/ExecuteResponse.d.ts +25 -0
  64. package/src/types/ExecuteResponse.js +7 -0
  65. package/src/types/ExecuteResponse.js.map +1 -0
  66. package/src/types/Pty.d.ts +47 -0
  67. package/src/types/Pty.js +7 -0
  68. package/src/types/Pty.js.map +1 -0
  69. package/src/utils/ArtifactParser.d.ts +13 -0
  70. package/src/utils/ArtifactParser.js +55 -0
  71. package/src/utils/ArtifactParser.js.map +1 -0
  72. package/src/utils/Binary.d.ts +38 -0
  73. package/src/utils/Binary.js +168 -0
  74. package/src/utils/Binary.js.map +1 -0
  75. package/src/utils/FileTransfer.d.ts +14 -0
  76. package/src/utils/FileTransfer.js +216 -0
  77. package/src/utils/FileTransfer.js.map +1 -0
  78. package/src/utils/Import.d.ts +97 -0
  79. package/src/utils/Import.js +79 -0
  80. package/src/utils/Import.js.map +1 -0
  81. package/src/utils/Multipart.d.ts +26 -0
  82. package/src/utils/Multipart.js +113 -0
  83. package/src/utils/Multipart.js.map +1 -0
  84. package/src/utils/Runtime.d.ts +43 -0
  85. package/src/utils/Runtime.js +95 -0
  86. package/src/utils/Runtime.js.map +1 -0
  87. package/src/utils/Stream.d.ts +19 -0
  88. package/src/utils/Stream.js +364 -0
  89. package/src/utils/Stream.js.map +1 -0
  90. package/src/utils/WebSocket.d.ts +9 -0
  91. package/src/utils/WebSocket.js +26 -0
  92. package/src/utils/WebSocket.js.map +1 -0
  93. package/src/utils/otel.decorator.d.ts +82 -0
  94. package/src/utils/otel.decorator.js +141 -0
  95. package/src/utils/otel.decorator.js.map +1 -0
package/README.md ADDED
@@ -0,0 +1,180 @@
1
+ # Daytona TypeScript SDK
2
+
3
+ The official TypeScript SDK for [Daytona](https://daytona.io), an open-source, secure and elastic infrastructure for running AI-generated code. Daytona provides full composable computers — [sandboxes](https://www.daytona.io/docs/en/sandboxes/) — that you can manage programmatically using the Daytona SDK.
4
+
5
+ The SDK provides an interface for sandbox management, file system operations, Git operations, language server protocol support, process and code execution, and computer use. For more information, see the [documentation](https://www.daytona.io/docs/en/typescript-sdk/).
6
+
7
+ ## Installation
8
+
9
+ Install the package using **npm**:
10
+
11
+ ```bash
12
+ npm install @daytona/sdk
13
+ ```
14
+
15
+ or using **yarn**:
16
+
17
+ ```bash
18
+ yarn add @daytona/sdk
19
+ ```
20
+
21
+ ## Get API key
22
+
23
+ Generate an API key from the [Daytona Dashboard ↗](https://app.daytona.io/dashboard/keys) to authenticate SDK requests and access Daytona services. For more information, see the [API keys](https://www.daytona.io/docs/en/api-keys/) documentation.
24
+
25
+ ## Configuration
26
+
27
+ Configure the SDK using [environment variables](https://www.daytona.io/docs/en/configuration/#environment-variables) or by passing a [configuration object](https://www.daytona.io/docs/en/configuration/#configuration-in-code):
28
+
29
+ - `DAYTONA_API_KEY`: Your Daytona [API key](https://www.daytona.io/docs/en/api-keys/)
30
+ - `DAYTONA_API_URL`: The Daytona [API URL](https://www.daytona.io/docs/en/tools/api/)
31
+ - `DAYTONA_TARGET`: Your target [region](https://www.daytona.io/docs/en/regions/) environment (e.g. `us`, `eu`)
32
+
33
+ ```typescript
34
+ import { Daytona } from '@daytona/sdk'
35
+
36
+ // Initialize with environment variables
37
+ const daytona = new Daytona();
38
+
39
+ // Initialize with configuration object
40
+ const daytona = new Daytona({
41
+ apiKey: 'YOUR_API_KEY',
42
+ apiUrl: 'YOUR_API_URL',
43
+ target: 'us',
44
+ });
45
+ ```
46
+
47
+ ## Create a sandbox
48
+
49
+ Create a sandbox to run your code securely in an isolated environment.
50
+
51
+ ```typescript
52
+ import { Daytona } from '@daytona/sdk'
53
+
54
+ const daytona = new Daytona({apiKey: "YOUR_API_KEY"});
55
+ const sandbox = await daytona.create({
56
+ language: 'typescript'
57
+ });
58
+ const response = await sandbox.process.codeRun('console.log("Hello World!")');
59
+ console.log(response.result);
60
+ ```
61
+
62
+ ## Examples and guides
63
+
64
+ Daytona provides [examples](https://www.daytona.io/docs/en/getting-started/#examples) and [guides](https://www.daytona.io/docs/en/guides/) for common sandbox operations, best practices, and a wide range of topics, from basic usage to advanced topics, showcasing various types of integrations between Daytona and other tools.
65
+
66
+ ### Create a sandbox with custom resources
67
+
68
+ Create a sandbox with [custom resources](https://www.daytona.io/docs/en/sandboxes/#resources) (CPU, memory, disk).
69
+
70
+ ```typescript
71
+ import { Daytona, Image } from '@daytona/sdk';
72
+
73
+ const daytona = new Daytona();
74
+ const sandbox = await daytona.create({
75
+ image: Image.debianSlim('3.12'),
76
+ resources: { cpu: 2, memory: 4, disk: 8 }
77
+ });
78
+ ```
79
+
80
+ ### Create an ephemeral sandbox
81
+
82
+ Create an [ephemeral sandbox](https://www.daytona.io/docs/en/sandboxes/#ephemeral-sandboxes) that is automatically deleted when stopped.
83
+
84
+ ```typescript
85
+ import { Daytona } from '@daytona/sdk';
86
+
87
+ const daytona = new Daytona();
88
+ const sandbox = await daytona.create({
89
+ ephemeral: true,
90
+ autoStopInterval: 5
91
+ });
92
+ ```
93
+
94
+ ### Create a sandbox from a snapshot
95
+
96
+ Create a sandbox from a [snapshot](https://www.daytona.io/docs/en/snapshots/).
97
+
98
+ ```typescript
99
+ import { Daytona } from '@daytona/sdk';
100
+
101
+ const daytona = new Daytona();
102
+ const sandbox = await daytona.create({
103
+ snapshot: 'my-snapshot-name',
104
+ language: 'typescript'
105
+ });
106
+ ```
107
+
108
+ ### Execute commands
109
+
110
+ Execute commands in the sandbox.
111
+
112
+ ```typescript
113
+ // Execute a shell command
114
+ const response = await sandbox.process.executeCommand('echo "Hello, World!"')
115
+ console.log(response.result)
116
+
117
+ // Run TypeScript code
118
+ const response = await sandbox.process.codeRun(`
119
+ const x = 10
120
+ const y = 20
121
+ console.log(\`Sum: \${x + y}\`)
122
+ `)
123
+ console.log(response.result)
124
+ ```
125
+
126
+ ### File operations
127
+
128
+ Upload, download, and search files in the sandbox.
129
+
130
+ ```typescript
131
+ // Upload a file
132
+ await sandbox.fs.uploadFile(Buffer.from('Hello, World!'), 'path/to/file.txt')
133
+
134
+ // Download a file
135
+ const content = await sandbox.fs.downloadFile('path/to/file.txt')
136
+
137
+ // Search for files
138
+ const matches = await sandbox.fs.findFiles(root_dir, 'search_pattern')
139
+ ```
140
+
141
+ ### Git operations
142
+
143
+ Clone, list branches, and add files to the sandbox.
144
+
145
+ ```typescript
146
+ // Clone a repository
147
+ await sandbox.git.clone('https://github.com/example/repo', 'path/to/clone')
148
+
149
+ // List branches
150
+ const branches = await sandbox.git.branches('path/to/repo')
151
+
152
+ // Add files
153
+ await sandbox.git.add('path/to/repo', ['file1.txt', 'file2.txt'])
154
+ ```
155
+
156
+ ### Language server protocol
157
+
158
+ Create and start a language server to get code completions, document symbols, and more.
159
+
160
+ ```typescript
161
+ // Create and start a language server
162
+ const lsp = await sandbox.createLspServer('typescript', 'path/to/project')
163
+ await lsp.start()
164
+
165
+ // Notify the lsp for the file
166
+ await lsp.didOpen('path/to/file.ts')
167
+
168
+ // Get document symbols
169
+ const symbols = await lsp.documentSymbols('path/to/file.ts')
170
+
171
+ // Get completions
172
+ const completions = await lsp.completions('path/to/file.ts', {
173
+ line: 10,
174
+ character: 15,
175
+ })
176
+ ```
177
+
178
+ ## Contributing
179
+
180
+ Daytona is Open Source under the [Apache License 2.0](/libs/sdk-typescript//LICENSE), and is the [copyright of its contributors](/NOTICE). If you would like to contribute to the software, read the Developer Certificate of Origin Version 1.1 (https://developercertificate.org/). Afterwards, navigate to the [contributing guide](/CONTRIBUTING.md) to get started.
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@daytona/sdk",
3
+ "version": "0.161.0-alpha.1",
4
+ "description": "Daytona TypeScript SDK for sandbox management and code execution",
5
+ "main": "./src/index.js",
6
+ "types": "./src/index.d.ts",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/daytonaio/daytona.git"
10
+ },
11
+ "author": "Daytona Platforms Inc.",
12
+ "license": "Apache-2.0",
13
+ "bugs": {
14
+ "url": "https://github.com/daytonaio/daytona/issues"
15
+ },
16
+ "homepage": "https://www.daytona.io/docs",
17
+ "config": {
18
+ "docsDir": "../../apps/docs/src/content/docs/en/typescript-sdk"
19
+ },
20
+ "scripts": {
21
+ "docs": "bash -O extglob -c 'rm -rf $npm_package_config_docsDir/!(index.mdx)' && typedoc && rm -f $npm_package_config_docsDir/readme.mdx"
22
+ },
23
+ "keywords": [
24
+ "daytona",
25
+ "sandbox",
26
+ "typescript",
27
+ "sdk"
28
+ ],
29
+ "dependencies": {
30
+ "@aws-sdk/client-s3": "^3.787.0",
31
+ "@aws-sdk/lib-storage": "^3.798.0",
32
+ "@iarna/toml": "^2.2.5",
33
+ "@opentelemetry/api": "^1.9.0",
34
+ "@opentelemetry/exporter-trace-otlp-http": "^0.207.0",
35
+ "@opentelemetry/instrumentation-http": "^0.207.0",
36
+ "@opentelemetry/otlp-exporter-base": "0.207.0",
37
+ "@opentelemetry/resources": "2.2.0",
38
+ "@opentelemetry/sdk-node": "^0.207.0",
39
+ "@opentelemetry/sdk-trace-base": "^2.2.0",
40
+ "@opentelemetry/semantic-conventions": "^1.37.0",
41
+ "axios": "^1.13.5",
42
+ "busboy": "^1.0.0",
43
+ "dotenv": "^17.0.1",
44
+ "expand-tilde": "^2.0.2",
45
+ "fast-glob": "^3.3.0",
46
+ "form-data": "^4.0.4",
47
+ "isomorphic-ws": "^5.0.0",
48
+ "pathe": "^2.0.3",
49
+ "shell-quote": "^1.8.2",
50
+ "tar": "^7.5.11",
51
+ "@daytonaio/api-client": "0.161.0-alpha.1",
52
+ "@daytonaio/toolbox-api-client": "0.161.0-alpha.1"
53
+ },
54
+ "packageManager": "yarn@4.13.0",
55
+ "type": "commonjs"
56
+ }
@@ -0,0 +1,94 @@
1
+ import { InterpreterApi, InterpreterContext } from '@daytonaio/toolbox-api-client';
2
+ import { Configuration } from '@daytonaio/api-client';
3
+ import { ExecutionResult, RunCodeOptions } from './types/CodeInterpreter';
4
+ /**
5
+ * Handles Python code interpretation and execution within a Sandbox.
6
+ *
7
+ * Provides methods to execute code (currently only Python) in isolated interpreter contexts,
8
+ * manage contexts, and stream execution output via callbacks.
9
+ *
10
+ * For other languages, use the `codeRun` method from the `Process` interface, or execute the appropriate command directly in the sandbox terminal.
11
+ */
12
+ export declare class CodeInterpreter {
13
+ private readonly clientConfig;
14
+ private readonly apiClient;
15
+ private readonly getPreviewToken;
16
+ constructor(clientConfig: Configuration, apiClient: InterpreterApi, getPreviewToken: () => Promise<string>);
17
+ /**
18
+ * Run Python code in the sandbox.
19
+ *
20
+ * @param {string} code - Code to run.
21
+ * @param {RunCodeOptions} options - Execution options (context, envs, callbacks, timeout).
22
+ * @returns {Promise<ExecutionResult>} ExecutionResult containing stdout, stderr and optional error info.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const handleStdout = (msg: OutputMessage) => process.stdout.write(`STDOUT: ${msg.output}`)
27
+ * const handleStderr = (msg: OutputMessage) => process.stdout.write(`STDERR: ${msg.output}`)
28
+ * const handleError = (err: ExecutionError) =>
29
+ * console.error(`ERROR: ${err.name}: ${err.value}\n${err.traceback ?? ''}`)
30
+ *
31
+ * const code = `
32
+ * import sys
33
+ * import time
34
+ * for i in range(5):
35
+ * print(i)
36
+ * time.sleep(1)
37
+ * sys.stderr.write("Counting done!")
38
+ * `
39
+ *
40
+ * const result = await codeInterpreter.runCode(code, {
41
+ * onStdout: handleStdout,
42
+ * onStderr: handleStderr,
43
+ * onError: handleError,
44
+ * timeout: 10,
45
+ * })
46
+ * ```
47
+ */
48
+ runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
49
+ /**
50
+ * Create a new isolated interpreter context.
51
+ *
52
+ * @param {string} [cwd] - Working directory for the context. Uses sandbox working directory if omitted.
53
+ *
54
+ * @returns {Promise<InterpreterContext>} The created context.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * const ctx = await sandbox.codeInterpreter.createContext()
59
+ * await sandbox.codeInterpreter.runCode('x = 10', { context: ctx })
60
+ * await sandbox.codeInterpreter.deleteContext(ctx.id!)
61
+ * ```
62
+ */
63
+ createContext(cwd?: string): Promise<InterpreterContext>;
64
+ /**
65
+ * List all user-created interpreter contexts (default context is excluded).
66
+ *
67
+ * @returns {Promise<InterpreterContext[]>} List of contexts.
68
+ *
69
+ * @example
70
+ * ```ts
71
+ * const contexts = await sandbox.codeInterpreter.listContexts()
72
+ * for (const ctx of contexts) {
73
+ * console.log(ctx.id, ctx.language, ctx.cwd)
74
+ * }
75
+ * ```
76
+ */
77
+ listContexts(): Promise<InterpreterContext[]>;
78
+ /**
79
+ * Delete an interpreter context and shut down its worker process.
80
+ *
81
+ * @param {InterpreterContext} context - Context to delete.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * const ctx = await sandbox.codeInterpreter.createContext()
86
+ * // ... use context ...
87
+ * await sandbox.codeInterpreter.deleteContext(ctx)
88
+ * ```
89
+ */
90
+ deleteContext(context: InterpreterContext): Promise<void>;
91
+ private extractMessageText;
92
+ private normalizeCloseEvent;
93
+ private createCloseError;
94
+ }
@@ -0,0 +1,297 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2025 Daytona Platforms Inc.
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.CodeInterpreter = void 0;
8
+ const tslib_1 = require("tslib");
9
+ /**
10
+ * @module code-interpreter
11
+ */
12
+ const isomorphic_ws_1 = tslib_1.__importDefault(require("isomorphic-ws"));
13
+ const DaytonaError_1 = require("./errors/DaytonaError");
14
+ const WebSocket_1 = require("./utils/WebSocket");
15
+ const WEBSOCKET_TIMEOUT_CODE = 4008;
16
+ /**
17
+ * Handles Python code interpretation and execution within a Sandbox.
18
+ *
19
+ * Provides methods to execute code (currently only Python) in isolated interpreter contexts,
20
+ * manage contexts, and stream execution output via callbacks.
21
+ *
22
+ * For other languages, use the `codeRun` method from the `Process` interface, or execute the appropriate command directly in the sandbox terminal.
23
+ */
24
+ class CodeInterpreter {
25
+ clientConfig;
26
+ apiClient;
27
+ getPreviewToken;
28
+ constructor(clientConfig, apiClient, getPreviewToken) {
29
+ this.clientConfig = clientConfig;
30
+ this.apiClient = apiClient;
31
+ this.getPreviewToken = getPreviewToken;
32
+ }
33
+ /**
34
+ * Run Python code in the sandbox.
35
+ *
36
+ * @param {string} code - Code to run.
37
+ * @param {RunCodeOptions} options - Execution options (context, envs, callbacks, timeout).
38
+ * @returns {Promise<ExecutionResult>} ExecutionResult containing stdout, stderr and optional error info.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * const handleStdout = (msg: OutputMessage) => process.stdout.write(`STDOUT: ${msg.output}`)
43
+ * const handleStderr = (msg: OutputMessage) => process.stdout.write(`STDERR: ${msg.output}`)
44
+ * const handleError = (err: ExecutionError) =>
45
+ * console.error(`ERROR: ${err.name}: ${err.value}\n${err.traceback ?? ''}`)
46
+ *
47
+ * const code = `
48
+ * import sys
49
+ * import time
50
+ * for i in range(5):
51
+ * print(i)
52
+ * time.sleep(1)
53
+ * sys.stderr.write("Counting done!")
54
+ * `
55
+ *
56
+ * const result = await codeInterpreter.runCode(code, {
57
+ * onStdout: handleStdout,
58
+ * onStderr: handleStderr,
59
+ * onError: handleError,
60
+ * timeout: 10,
61
+ * })
62
+ * ```
63
+ */
64
+ async runCode(code, options = {}) {
65
+ if (!code || !code.trim()) {
66
+ throw new DaytonaError_1.DaytonaError('Code is required for execution');
67
+ }
68
+ const url = `${this.clientConfig.basePath.replace(/^http/, 'ws')}/process/interpreter/execute`;
69
+ const ws = await (0, WebSocket_1.createSandboxWebSocket)(url, this.clientConfig.baseOptions?.headers || {}, this.getPreviewToken);
70
+ const result = { stdout: '', stderr: '' };
71
+ return new Promise((resolve, reject) => {
72
+ let settled = false;
73
+ const cleanup = () => {
74
+ detach();
75
+ try {
76
+ if (ws.readyState === isomorphic_ws_1.default.OPEN || ws.readyState === isomorphic_ws_1.default.CONNECTING) {
77
+ ws.close();
78
+ }
79
+ }
80
+ catch {
81
+ /* ignore */
82
+ }
83
+ };
84
+ const fail = (error) => {
85
+ if (settled)
86
+ return;
87
+ settled = true;
88
+ cleanup();
89
+ reject(error);
90
+ };
91
+ const succeed = () => {
92
+ if (settled)
93
+ return;
94
+ settled = true;
95
+ cleanup();
96
+ resolve(result);
97
+ };
98
+ const handleOpen = () => {
99
+ const payload = { code };
100
+ const context = options.context;
101
+ if (context?.id) {
102
+ payload.contextId = context.id;
103
+ }
104
+ if (options.envs) {
105
+ payload.envs = options.envs;
106
+ }
107
+ payload.timeout = options.timeout;
108
+ ws.send(JSON.stringify(payload));
109
+ };
110
+ const handleMessage = async (event) => {
111
+ try {
112
+ const text = await this.extractMessageText(event);
113
+ if (!text) {
114
+ return;
115
+ }
116
+ const chunk = JSON.parse(text);
117
+ const chunkType = chunk.type;
118
+ if (chunkType === 'stdout') {
119
+ const stdout = chunk.text ?? '';
120
+ result.stdout += stdout;
121
+ if (options.onStdout) {
122
+ await options.onStdout({ output: stdout });
123
+ }
124
+ }
125
+ else if (chunkType === 'stderr') {
126
+ const stderr = chunk.text ?? '';
127
+ result.stderr += stderr;
128
+ if (options.onStderr) {
129
+ await options.onStderr({ output: stderr });
130
+ }
131
+ }
132
+ else if (chunkType === 'error') {
133
+ const error = {
134
+ name: chunk.name ?? '',
135
+ value: chunk.value ?? '',
136
+ traceback: chunk.traceback ?? '',
137
+ };
138
+ result.error = error;
139
+ if (options.onError) {
140
+ await options.onError(error);
141
+ }
142
+ }
143
+ else if (chunkType === 'control') {
144
+ const controlText = chunk.text ?? '';
145
+ if (controlText === 'completed' || controlText === 'interrupted') {
146
+ succeed();
147
+ }
148
+ }
149
+ }
150
+ catch {
151
+ // Ignore invalid JSON payloads
152
+ }
153
+ };
154
+ const handleClose = (event, reason) => {
155
+ if (settled)
156
+ return;
157
+ const { code, message } = this.normalizeCloseEvent(event, reason);
158
+ if (code !== 1000 && code !== 1001) {
159
+ fail(this.createCloseError(code, message));
160
+ return;
161
+ }
162
+ succeed();
163
+ };
164
+ const handleError = (error) => {
165
+ fail(new DaytonaError_1.DaytonaError(`Failed to execute code: ${error.message ?? String(error)}`));
166
+ };
167
+ const detach = () => {
168
+ if ('removeEventListener' in ws) {
169
+ ws.removeEventListener('open', handleOpen);
170
+ ws.removeEventListener('message', handleMessage);
171
+ ws.removeEventListener('close', handleClose);
172
+ ws.removeEventListener('error', handleError);
173
+ }
174
+ if ('off' in ws) {
175
+ ;
176
+ ws.off('open', handleOpen);
177
+ ws.off('message', handleMessage);
178
+ ws.off('close', handleClose);
179
+ ws.off('error', handleError);
180
+ }
181
+ else if ('removeListener' in ws) {
182
+ ;
183
+ ws.removeListener('open', handleOpen);
184
+ ws.removeListener('message', handleMessage);
185
+ ws.removeListener('close', handleClose);
186
+ ws.removeListener('error', handleError);
187
+ }
188
+ };
189
+ if ('addEventListener' in ws) {
190
+ ws.addEventListener('open', handleOpen);
191
+ ws.addEventListener('message', handleMessage);
192
+ ws.addEventListener('close', handleClose);
193
+ ws.addEventListener('error', handleError);
194
+ }
195
+ else if ('on' in ws) {
196
+ ;
197
+ ws.on('open', handleOpen);
198
+ ws.on('message', handleMessage);
199
+ ws.on('close', handleClose);
200
+ ws.on('error', handleError);
201
+ }
202
+ else {
203
+ throw new DaytonaError_1.DaytonaError('Unsupported WebSocket implementation');
204
+ }
205
+ });
206
+ }
207
+ /**
208
+ * Create a new isolated interpreter context.
209
+ *
210
+ * @param {string} [cwd] - Working directory for the context. Uses sandbox working directory if omitted.
211
+ *
212
+ * @returns {Promise<InterpreterContext>} The created context.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * const ctx = await sandbox.codeInterpreter.createContext()
217
+ * await sandbox.codeInterpreter.runCode('x = 10', { context: ctx })
218
+ * await sandbox.codeInterpreter.deleteContext(ctx.id!)
219
+ * ```
220
+ */
221
+ async createContext(cwd) {
222
+ return (await this.apiClient.createInterpreterContext({ cwd })).data;
223
+ }
224
+ /**
225
+ * List all user-created interpreter contexts (default context is excluded).
226
+ *
227
+ * @returns {Promise<InterpreterContext[]>} List of contexts.
228
+ *
229
+ * @example
230
+ * ```ts
231
+ * const contexts = await sandbox.codeInterpreter.listContexts()
232
+ * for (const ctx of contexts) {
233
+ * console.log(ctx.id, ctx.language, ctx.cwd)
234
+ * }
235
+ * ```
236
+ */
237
+ async listContexts() {
238
+ return (await this.apiClient.listInterpreterContexts()).data.contexts ?? [];
239
+ }
240
+ /**
241
+ * Delete an interpreter context and shut down its worker process.
242
+ *
243
+ * @param {InterpreterContext} context - Context to delete.
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * const ctx = await sandbox.codeInterpreter.createContext()
248
+ * // ... use context ...
249
+ * await sandbox.codeInterpreter.deleteContext(ctx)
250
+ * ```
251
+ */
252
+ async deleteContext(context) {
253
+ await this.apiClient.deleteInterpreterContext(context.id);
254
+ }
255
+ async extractMessageText(event) {
256
+ const data = event && typeof event === 'object' && 'data' in event ? event.data : event;
257
+ if (typeof data === 'string') {
258
+ return data;
259
+ }
260
+ if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
261
+ return new TextDecoder('utf-8').decode(new Uint8Array(data));
262
+ }
263
+ if (typeof Blob !== 'undefined' && data instanceof Blob) {
264
+ return await data.text();
265
+ }
266
+ if (ArrayBuffer.isView(data)) {
267
+ return new TextDecoder('utf-8').decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
268
+ }
269
+ if (data == null) {
270
+ return '';
271
+ }
272
+ return data.toString();
273
+ }
274
+ normalizeCloseEvent(event, reason) {
275
+ if (typeof event === 'number') {
276
+ return {
277
+ code: event,
278
+ message: reason ? reason.toString('utf-8') : '',
279
+ };
280
+ }
281
+ return {
282
+ code: event.code,
283
+ message: event.reason,
284
+ };
285
+ }
286
+ createCloseError(code, message) {
287
+ if (code === WEBSOCKET_TIMEOUT_CODE) {
288
+ return new DaytonaError_1.DaytonaTimeoutError('Execution timed out: operation exceeded the configured `timeout`. Provide a larger value if needed.');
289
+ }
290
+ if (message) {
291
+ return new DaytonaError_1.DaytonaError(message + ` (close code ${code})`);
292
+ }
293
+ return new DaytonaError_1.DaytonaError(`Code execution failed: WebSocket closed with code ${code}`);
294
+ }
295
+ }
296
+ exports.CodeInterpreter = CodeInterpreter;
297
+ //# sourceMappingURL=CodeInterpreter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CodeInterpreter.js","sourceRoot":"","sources":["../../../../libs/sdk-typescript/src/CodeInterpreter.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;AAEH;;GAEG;AAEH,0EAAqC;AAGrC,wDAAyE;AAEzE,iDAA0D;AAO1D,MAAM,sBAAsB,GAAG,IAAI,CAAA;AAEnC;;;;;;;GAOG;AACH,MAAa,eAAe;IAEP;IACA;IACA;IAHnB,YACmB,YAA2B,EAC3B,SAAyB,EACzB,eAAsC;QAFtC,iBAAY,GAAZ,YAAY,CAAe;QAC3B,cAAS,GAAT,SAAS,CAAgB;QACzB,oBAAe,GAAf,eAAe,CAAuB;IACtD,CAAC;IAEJ;;;;;;;;;;;;;;;;;;;;;;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