@meistrari/sandbox-sdk 0.1.5 → 1.0.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.
- package/README.md +79 -77
- package/dist/index.cjs +77 -28
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +73 -24
- package/package.json +26 -26
package/README.md
CHANGED
|
@@ -17,14 +17,14 @@ import { sandbox, DataTokenAuthStrategy } from '@meistrari/sandbox-sdk'
|
|
|
17
17
|
|
|
18
18
|
// Create client
|
|
19
19
|
const client = sandbox({
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
apiUrl: 'https://sandbox.meistrari.com',
|
|
21
|
+
auth: new DataTokenAuthStrategy(dataToken),
|
|
22
22
|
})
|
|
23
23
|
|
|
24
24
|
// Execute code
|
|
25
25
|
const run = await client.createRunAndWait({
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
code: 'console.log("Hello, World!")',
|
|
27
|
+
language: 'typescript',
|
|
28
28
|
})
|
|
29
29
|
|
|
30
30
|
console.log(run.stdout) // "Hello, World!"
|
|
@@ -37,15 +37,15 @@ console.log(run.stdout) // "Hello, World!"
|
|
|
37
37
|
```typescript
|
|
38
38
|
// One-shot execution (no persistent sandbox)
|
|
39
39
|
const run = await client.createRunAndWait({
|
|
40
|
-
|
|
40
|
+
code: `
|
|
41
41
|
const result = 1 + 1
|
|
42
42
|
console.log(result)
|
|
43
43
|
`,
|
|
44
|
-
|
|
44
|
+
language: 'typescript',
|
|
45
45
|
})
|
|
46
46
|
|
|
47
|
-
console.log(run.stdout)
|
|
48
|
-
console.log(run.exitCode)
|
|
47
|
+
console.log(run.stdout) // "2"
|
|
48
|
+
console.log(run.exitCode) // 0
|
|
49
49
|
console.log(run.isSuccess) // true
|
|
50
50
|
```
|
|
51
51
|
|
|
@@ -56,8 +56,8 @@ import { Sandbox } from '@meistrari/sandbox-sdk'
|
|
|
56
56
|
|
|
57
57
|
// Create a persistent sandbox
|
|
58
58
|
const sandbox = await Sandbox.create(client, {
|
|
59
|
-
|
|
60
|
-
|
|
59
|
+
memSize: 512,
|
|
60
|
+
cpuSize: 1.0,
|
|
61
61
|
})
|
|
62
62
|
|
|
63
63
|
// Execute multiple commands in the same sandbox
|
|
@@ -122,8 +122,8 @@ const result = await sandbox.runCode(`
|
|
|
122
122
|
console.log(_.pick(data, ['name', 'age']))
|
|
123
123
|
console.log(schema.parse(data))
|
|
124
124
|
`, {
|
|
125
|
-
|
|
126
|
-
|
|
125
|
+
language: 'typescript',
|
|
126
|
+
libraries: ['lodash', 'zod'],
|
|
127
127
|
})
|
|
128
128
|
|
|
129
129
|
console.log(result.stdout)
|
|
@@ -140,11 +140,11 @@ const result = await sandbox.runCode(`
|
|
|
140
140
|
console.log('API Key:', process.env.API_KEY)
|
|
141
141
|
console.log('Environment:', process.env.NODE_ENV)
|
|
142
142
|
`, {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
143
|
+
language: 'typescript',
|
|
144
|
+
envs: {
|
|
145
|
+
API_KEY: 'secret-key-123',
|
|
146
|
+
NODE_ENV: 'production',
|
|
147
|
+
},
|
|
148
148
|
})
|
|
149
149
|
```
|
|
150
150
|
|
|
@@ -163,19 +163,19 @@ const result = await sandbox.runCode(`
|
|
|
163
163
|
console.log('Config:', config)
|
|
164
164
|
console.log('Data lines:', data.split('\\n').length)
|
|
165
165
|
`, {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
166
|
+
language: 'typescript',
|
|
167
|
+
files: [
|
|
168
|
+
{
|
|
169
|
+
name: 'config.json',
|
|
170
|
+
content: JSON.stringify({ apiUrl: 'https://api.example.com', timeout: 5000 }),
|
|
171
|
+
encoding: 'utf8',
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
name: 'data.csv',
|
|
175
|
+
content: 'name,age\\nJohn,30\\nJane,25',
|
|
176
|
+
encoding: 'utf8',
|
|
177
|
+
},
|
|
178
|
+
],
|
|
179
179
|
})
|
|
180
180
|
```
|
|
181
181
|
|
|
@@ -196,18 +196,18 @@ const result = await sandbox.runCode(`
|
|
|
196
196
|
console.log('Parsed records:', parsed.data.length)
|
|
197
197
|
console.log('First record:', JSON.stringify(parsed.data[0]))
|
|
198
198
|
`, {
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
},
|
|
204
|
-
files: [
|
|
205
|
-
{
|
|
206
|
-
name: 'users.csv',
|
|
207
|
-
content: 'id,name,email\\n1,John,john@example.com\\n2,Jane,jane@example.com',
|
|
208
|
-
encoding: 'utf8',
|
|
199
|
+
language: 'typescript',
|
|
200
|
+
libraries: ['papaparse'],
|
|
201
|
+
envs: {
|
|
202
|
+
PARSER_API_KEY: 'pk_live_abc123xyz',
|
|
209
203
|
},
|
|
210
|
-
|
|
204
|
+
files: [
|
|
205
|
+
{
|
|
206
|
+
name: 'users.csv',
|
|
207
|
+
content: 'id,name,email\\n1,John,john@example.com\\n2,Jane,jane@example.com',
|
|
208
|
+
encoding: 'utf8',
|
|
209
|
+
},
|
|
210
|
+
],
|
|
211
211
|
})
|
|
212
212
|
|
|
213
213
|
await sandbox.kill()
|
|
@@ -217,10 +217,10 @@ await sandbox.kill()
|
|
|
217
217
|
|
|
218
218
|
```typescript
|
|
219
219
|
const result = await sandbox.runCode(longRunningScript, {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
220
|
+
language: 'typescript',
|
|
221
|
+
onStdout: ({ line }) => console.log('[stdout]', line),
|
|
222
|
+
onStderr: ({ line }) => console.log('[stderr]', line),
|
|
223
|
+
onError: error => console.error('[error]', error),
|
|
224
224
|
})
|
|
225
225
|
```
|
|
226
226
|
|
|
@@ -240,11 +240,11 @@ await sandbox.runCode('console.log("I am back!")')
|
|
|
240
240
|
|
|
241
241
|
Creates a new Sandbox client instance.
|
|
242
242
|
|
|
243
|
-
```
|
|
243
|
+
```javascript
|
|
244
244
|
const client = sandbox({
|
|
245
245
|
apiUrl: string, // Sandbox API URL
|
|
246
246
|
auth: AuthStrategy, // Authentication strategy
|
|
247
|
-
timeout
|
|
247
|
+
timeout: number, // Request timeout in ms (default: 300000, optional)
|
|
248
248
|
})
|
|
249
249
|
```
|
|
250
250
|
|
|
@@ -301,34 +301,34 @@ const client = sandbox({
|
|
|
301
301
|
type Status = 'pending' | 'running' | 'completed' | 'failed' | 'timeout' | 'cancelled'
|
|
302
302
|
|
|
303
303
|
interface CreateRunRequest {
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
304
|
+
code: string
|
|
305
|
+
language?: 'javascript' | 'typescript' | 'python' | 'bash'
|
|
306
|
+
libraries?: string[]
|
|
307
|
+
env?: Record<string, string>
|
|
308
|
+
files?: FileInput[]
|
|
309
|
+
memSize?: number // MB (default: 512)
|
|
310
|
+
cpuSize?: number // cores (default: 1.0)
|
|
311
|
+
timeoutMs?: number // ms (default: 300000)
|
|
312
|
+
sandboxId?: string // Use existing sandbox
|
|
313
|
+
persistent?: boolean // Keep sandbox after execution
|
|
314
314
|
}
|
|
315
315
|
|
|
316
316
|
interface RunCodeOptions {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
317
|
+
language?: 'typescript' | 'javascript' | 'python' | 'bash'
|
|
318
|
+
envs?: Record<string, string>
|
|
319
|
+
timeoutMs?: number
|
|
320
|
+
libraries?: string[] // npm packages to install
|
|
321
|
+
files?: FileInput[] // input files to provide
|
|
322
|
+
onStdout?: (data: { line: string }) => void
|
|
323
|
+
onStderr?: (data: { line: string }) => void
|
|
324
|
+
onError?: (error: Error) => void
|
|
325
325
|
}
|
|
326
326
|
|
|
327
327
|
interface FileInput {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
328
|
+
name: string // filename
|
|
329
|
+
content: string // file content
|
|
330
|
+
encoding: 'utf8' | 'base64'
|
|
331
|
+
path?: string // optional custom path
|
|
332
332
|
}
|
|
333
333
|
```
|
|
334
334
|
|
|
@@ -339,10 +339,11 @@ This SDK is designed to be compatible with E2B's `SandboxLike` interface, making
|
|
|
339
339
|
```typescript
|
|
340
340
|
// E2B
|
|
341
341
|
import { Sandbox } from '@e2b/code-interpreter'
|
|
342
|
-
const sandbox = await Sandbox.create(templateId, { apiKey })
|
|
343
342
|
|
|
344
343
|
// Sandbox (drop-in replacement)
|
|
345
344
|
import { Sandbox, sandbox, DataTokenAuthStrategy } from '@meistrari/sandbox-sdk'
|
|
345
|
+
|
|
346
|
+
const sandbox = await Sandbox.create(templateId, { apiKey })
|
|
346
347
|
const client = sandbox({ apiUrl, auth: new DataTokenAuthStrategy(token) })
|
|
347
348
|
const sandbox = await Sandbox.create(client)
|
|
348
349
|
|
|
@@ -358,13 +359,14 @@ await sandbox.kill()
|
|
|
358
359
|
import { FetchError } from '@meistrari/sandbox-sdk'
|
|
359
360
|
|
|
360
361
|
try {
|
|
361
|
-
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
362
|
+
const run = await client.createRunAndWait({ code: 'invalid(' })
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
if (error instanceof FetchError) {
|
|
366
|
+
console.error(`API Error: ${error.message}`)
|
|
367
|
+
console.error(`Status: ${error.status}`)
|
|
368
|
+
console.error(`URL: ${error.url}`)
|
|
369
|
+
}
|
|
368
370
|
}
|
|
369
371
|
```
|
|
370
372
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const node_buffer = require('node:buffer');
|
|
3
4
|
const eventsourceParser = require('eventsource-parser');
|
|
4
5
|
|
|
5
6
|
class FetchError extends Error {
|
|
@@ -24,8 +25,7 @@ class FetchError extends Error {
|
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
async function* parseSSEStream(response) {
|
|
27
|
-
|
|
28
|
-
if (!reader)
|
|
28
|
+
if (!response.body)
|
|
29
29
|
throw new Error("No response body");
|
|
30
30
|
const decoder = new TextDecoder();
|
|
31
31
|
const events = [];
|
|
@@ -39,11 +39,8 @@ async function* parseSSEStream(response) {
|
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
});
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
if (done)
|
|
45
|
-
break;
|
|
46
|
-
parser.feed(decoder.decode(value, { stream: true }));
|
|
42
|
+
for await (const chunk of response.body) {
|
|
43
|
+
parser.feed(decoder.decode(chunk, { stream: true }));
|
|
47
44
|
while (events.length > 0) {
|
|
48
45
|
yield events.shift();
|
|
49
46
|
}
|
|
@@ -81,16 +78,16 @@ class Sandbox {
|
|
|
81
78
|
__publicField$2(this, "commands");
|
|
82
79
|
__publicField$2(this, "timeoutMs", 3e5);
|
|
83
80
|
this.sandboxId = sandboxId;
|
|
84
|
-
const readFile = (path, options) => {
|
|
85
|
-
return this.client.readFile(sandboxId, path, options);
|
|
81
|
+
const readFile = async (path, options) => {
|
|
82
|
+
return await this.client.readFile(sandboxId, path, options);
|
|
86
83
|
};
|
|
87
84
|
this.files = {
|
|
88
|
-
write: (path, content) => this.client.writeFile(sandboxId, path, content),
|
|
85
|
+
write: async (path, content) => await this.client.writeFile(sandboxId, path, content),
|
|
89
86
|
read: readFile,
|
|
90
|
-
exists: (path) => this.client.fileExists(sandboxId, path),
|
|
91
|
-
remove: (path) => this.client.deleteFile(sandboxId, path),
|
|
92
|
-
list: (directory) => this.client.listFiles(sandboxId, directory),
|
|
93
|
-
uploadBulk: (files) => this.client.uploadBulkFiles(sandboxId, files)
|
|
87
|
+
exists: async (path) => await this.client.fileExists(sandboxId, path),
|
|
88
|
+
remove: async (path) => await this.client.deleteFile(sandboxId, path),
|
|
89
|
+
list: async (directory) => await this.client.listFiles(sandboxId, directory),
|
|
90
|
+
uploadBulk: async (files) => await this.client.uploadBulkFiles(sandboxId, files)
|
|
94
91
|
};
|
|
95
92
|
this.commands = {
|
|
96
93
|
run: async (command) => {
|
|
@@ -105,10 +102,10 @@ class Sandbox {
|
|
|
105
102
|
}
|
|
106
103
|
// Factory methods (static)
|
|
107
104
|
static async create(client, options = {}) {
|
|
108
|
-
return client.createSandbox(options);
|
|
105
|
+
return await client.createSandbox(options);
|
|
109
106
|
}
|
|
110
107
|
static async connect(client, sandboxId) {
|
|
111
|
-
return client.connectToSandbox(sandboxId);
|
|
108
|
+
return await client.connectToSandbox(sandboxId);
|
|
112
109
|
}
|
|
113
110
|
// Normalize language aliases ('ts' -> 'typescript', 'js' -> 'javascript')
|
|
114
111
|
normalizeLanguage(lang) {
|
|
@@ -116,7 +113,9 @@ class Sandbox {
|
|
|
116
113
|
return "typescript";
|
|
117
114
|
if (lang === "js")
|
|
118
115
|
return "javascript";
|
|
119
|
-
|
|
116
|
+
if (lang === "typescript" || lang === "javascript" || lang === "python" || lang === "bash")
|
|
117
|
+
return lang;
|
|
118
|
+
return "typescript";
|
|
120
119
|
}
|
|
121
120
|
// Main execution method (compatible with E2B and agent-api)
|
|
122
121
|
async runCode(script, options = {}) {
|
|
@@ -134,10 +133,12 @@ class Sandbox {
|
|
|
134
133
|
});
|
|
135
134
|
for await (const event of stream) {
|
|
136
135
|
if (event.type === "stdout" && event.content) {
|
|
137
|
-
stdout += event.content
|
|
136
|
+
stdout += `${event.content}
|
|
137
|
+
`;
|
|
138
138
|
await options.onStdout?.({ line: event.content });
|
|
139
139
|
} else if (event.type === "stderr" && event.content) {
|
|
140
|
-
stderr += event.content
|
|
140
|
+
stderr += `${event.content}
|
|
141
|
+
`;
|
|
141
142
|
await options.onStderr?.({ line: event.content });
|
|
142
143
|
} else if (event.type === "status" && event.metadata?.exitCode !== void 0) {
|
|
143
144
|
exitCode = event.metadata.exitCode;
|
|
@@ -150,8 +151,24 @@ class Sandbox {
|
|
|
150
151
|
return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode };
|
|
151
152
|
}
|
|
152
153
|
// Lifecycle methods
|
|
154
|
+
// Retries on 409 (active runs) to handle eventual consistency between
|
|
155
|
+
// the SSE stream completion and the DB status update
|
|
153
156
|
async kill() {
|
|
154
|
-
|
|
157
|
+
const maxAttempts = 5;
|
|
158
|
+
const baseDelayMs = 500;
|
|
159
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
160
|
+
try {
|
|
161
|
+
await this.client.deleteSandbox(this.sandboxId);
|
|
162
|
+
return;
|
|
163
|
+
} catch (error) {
|
|
164
|
+
const isConflict = error instanceof FetchError && error.status === 409;
|
|
165
|
+
if (isConflict && attempt < maxAttempts) {
|
|
166
|
+
await new Promise((resolve) => setTimeout(resolve, baseDelayMs * attempt));
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
155
172
|
}
|
|
156
173
|
async betaPause() {
|
|
157
174
|
}
|
|
@@ -241,7 +258,7 @@ class SandboxClient {
|
|
|
241
258
|
if (!res.ok) {
|
|
242
259
|
throw await FetchError.from(url, options.method ?? "GET", res);
|
|
243
260
|
}
|
|
244
|
-
return res.json();
|
|
261
|
+
return await res.json();
|
|
245
262
|
}
|
|
246
263
|
// === Runs ===
|
|
247
264
|
async createRun(request) {
|
|
@@ -253,7 +270,7 @@ class SandboxClient {
|
|
|
253
270
|
}
|
|
254
271
|
async createRunAndWait(request) {
|
|
255
272
|
const run = await this.createRun(request);
|
|
256
|
-
return run.waitForCompletion();
|
|
273
|
+
return await run.waitForCompletion();
|
|
257
274
|
}
|
|
258
275
|
async *streamRun(request) {
|
|
259
276
|
const url = `${this.apiUrl}/api/runs/stream`;
|
|
@@ -271,7 +288,39 @@ class SandboxClient {
|
|
|
271
288
|
if (!res.ok) {
|
|
272
289
|
throw await FetchError.from(url, "POST", res);
|
|
273
290
|
}
|
|
274
|
-
|
|
291
|
+
let capturedRunId;
|
|
292
|
+
try {
|
|
293
|
+
for await (const event of parseSSEStream(res)) {
|
|
294
|
+
if (event.type === "run_created" && event.runId) {
|
|
295
|
+
capturedRunId = event.runId;
|
|
296
|
+
}
|
|
297
|
+
yield event;
|
|
298
|
+
}
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (!capturedRunId) {
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
let run = await this.getRun(capturedRunId);
|
|
304
|
+
if (!run.isComplete) {
|
|
305
|
+
run = await run.waitForCompletion();
|
|
306
|
+
}
|
|
307
|
+
if (run.stdout) {
|
|
308
|
+
yield { type: "stdout", content: run.stdout };
|
|
309
|
+
}
|
|
310
|
+
if (run.stderr) {
|
|
311
|
+
yield { type: "stderr", content: run.stderr };
|
|
312
|
+
}
|
|
313
|
+
yield {
|
|
314
|
+
type: "done",
|
|
315
|
+
runId: capturedRunId,
|
|
316
|
+
sandboxId: run.sandboxId,
|
|
317
|
+
metadata: {
|
|
318
|
+
exitCode: run.exitCode ?? 0,
|
|
319
|
+
durationMs: run.durationMs,
|
|
320
|
+
errorMessage: run.errorMessage
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
275
324
|
}
|
|
276
325
|
async getRun(runId) {
|
|
277
326
|
const response = await this.fetch(`/api/runs/${runId}`);
|
|
@@ -284,7 +333,7 @@ class SandboxClient {
|
|
|
284
333
|
body: JSON.stringify(request)
|
|
285
334
|
});
|
|
286
335
|
await pollUntilComplete(
|
|
287
|
-
() => this.getSandboxStatus(response.data.sandboxId),
|
|
336
|
+
async () => await this.getSandboxStatus(response.data.sandboxId),
|
|
288
337
|
{ intervalMs: 200, maxAttempts: 150 }
|
|
289
338
|
// 30s max
|
|
290
339
|
);
|
|
@@ -309,7 +358,7 @@ class SandboxClient {
|
|
|
309
358
|
body: JSON.stringify({
|
|
310
359
|
name: path.split("/").pop(),
|
|
311
360
|
path,
|
|
312
|
-
content: isBuffer ? Buffer.from(content).toString("base64") : content,
|
|
361
|
+
content: isBuffer ? node_buffer.Buffer.from(content).toString("base64") : content,
|
|
313
362
|
encoding: isBuffer ? "base64" : "utf8"
|
|
314
363
|
})
|
|
315
364
|
});
|
|
@@ -322,14 +371,14 @@ class SandboxClient {
|
|
|
322
371
|
const format = options?.format ?? "text";
|
|
323
372
|
if (format === "blob") {
|
|
324
373
|
if (file.encoding === "base64") {
|
|
325
|
-
const bytes2 = Uint8Array.from(Buffer.from(file.content, "base64"));
|
|
374
|
+
const bytes2 = Uint8Array.from(node_buffer.Buffer.from(file.content, "base64"));
|
|
326
375
|
return new Blob([bytes2]);
|
|
327
376
|
}
|
|
328
|
-
const bytes = Uint8Array.from(Buffer.from(file.content, "utf8"));
|
|
377
|
+
const bytes = Uint8Array.from(node_buffer.Buffer.from(file.content, "utf8"));
|
|
329
378
|
return new Blob([bytes]);
|
|
330
379
|
}
|
|
331
380
|
if (file.encoding === "base64") {
|
|
332
|
-
return Buffer.from(file.content, "base64").toString("utf8");
|
|
381
|
+
return node_buffer.Buffer.from(file.content, "base64").toString("utf8");
|
|
333
382
|
}
|
|
334
383
|
return file.content;
|
|
335
384
|
}
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.mts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
1
2
|
import { createParser } from 'eventsource-parser';
|
|
2
3
|
|
|
3
4
|
class FetchError extends Error {
|
|
@@ -22,8 +23,7 @@ class FetchError extends Error {
|
|
|
22
23
|
}
|
|
23
24
|
|
|
24
25
|
async function* parseSSEStream(response) {
|
|
25
|
-
|
|
26
|
-
if (!reader)
|
|
26
|
+
if (!response.body)
|
|
27
27
|
throw new Error("No response body");
|
|
28
28
|
const decoder = new TextDecoder();
|
|
29
29
|
const events = [];
|
|
@@ -37,11 +37,8 @@ async function* parseSSEStream(response) {
|
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
});
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
if (done)
|
|
43
|
-
break;
|
|
44
|
-
parser.feed(decoder.decode(value, { stream: true }));
|
|
40
|
+
for await (const chunk of response.body) {
|
|
41
|
+
parser.feed(decoder.decode(chunk, { stream: true }));
|
|
45
42
|
while (events.length > 0) {
|
|
46
43
|
yield events.shift();
|
|
47
44
|
}
|
|
@@ -79,16 +76,16 @@ class Sandbox {
|
|
|
79
76
|
__publicField$2(this, "commands");
|
|
80
77
|
__publicField$2(this, "timeoutMs", 3e5);
|
|
81
78
|
this.sandboxId = sandboxId;
|
|
82
|
-
const readFile = (path, options) => {
|
|
83
|
-
return this.client.readFile(sandboxId, path, options);
|
|
79
|
+
const readFile = async (path, options) => {
|
|
80
|
+
return await this.client.readFile(sandboxId, path, options);
|
|
84
81
|
};
|
|
85
82
|
this.files = {
|
|
86
|
-
write: (path, content) => this.client.writeFile(sandboxId, path, content),
|
|
83
|
+
write: async (path, content) => await this.client.writeFile(sandboxId, path, content),
|
|
87
84
|
read: readFile,
|
|
88
|
-
exists: (path) => this.client.fileExists(sandboxId, path),
|
|
89
|
-
remove: (path) => this.client.deleteFile(sandboxId, path),
|
|
90
|
-
list: (directory) => this.client.listFiles(sandboxId, directory),
|
|
91
|
-
uploadBulk: (files) => this.client.uploadBulkFiles(sandboxId, files)
|
|
85
|
+
exists: async (path) => await this.client.fileExists(sandboxId, path),
|
|
86
|
+
remove: async (path) => await this.client.deleteFile(sandboxId, path),
|
|
87
|
+
list: async (directory) => await this.client.listFiles(sandboxId, directory),
|
|
88
|
+
uploadBulk: async (files) => await this.client.uploadBulkFiles(sandboxId, files)
|
|
92
89
|
};
|
|
93
90
|
this.commands = {
|
|
94
91
|
run: async (command) => {
|
|
@@ -103,10 +100,10 @@ class Sandbox {
|
|
|
103
100
|
}
|
|
104
101
|
// Factory methods (static)
|
|
105
102
|
static async create(client, options = {}) {
|
|
106
|
-
return client.createSandbox(options);
|
|
103
|
+
return await client.createSandbox(options);
|
|
107
104
|
}
|
|
108
105
|
static async connect(client, sandboxId) {
|
|
109
|
-
return client.connectToSandbox(sandboxId);
|
|
106
|
+
return await client.connectToSandbox(sandboxId);
|
|
110
107
|
}
|
|
111
108
|
// Normalize language aliases ('ts' -> 'typescript', 'js' -> 'javascript')
|
|
112
109
|
normalizeLanguage(lang) {
|
|
@@ -114,7 +111,9 @@ class Sandbox {
|
|
|
114
111
|
return "typescript";
|
|
115
112
|
if (lang === "js")
|
|
116
113
|
return "javascript";
|
|
117
|
-
|
|
114
|
+
if (lang === "typescript" || lang === "javascript" || lang === "python" || lang === "bash")
|
|
115
|
+
return lang;
|
|
116
|
+
return "typescript";
|
|
118
117
|
}
|
|
119
118
|
// Main execution method (compatible with E2B and agent-api)
|
|
120
119
|
async runCode(script, options = {}) {
|
|
@@ -132,10 +131,12 @@ class Sandbox {
|
|
|
132
131
|
});
|
|
133
132
|
for await (const event of stream) {
|
|
134
133
|
if (event.type === "stdout" && event.content) {
|
|
135
|
-
stdout += event.content
|
|
134
|
+
stdout += `${event.content}
|
|
135
|
+
`;
|
|
136
136
|
await options.onStdout?.({ line: event.content });
|
|
137
137
|
} else if (event.type === "stderr" && event.content) {
|
|
138
|
-
stderr += event.content
|
|
138
|
+
stderr += `${event.content}
|
|
139
|
+
`;
|
|
139
140
|
await options.onStderr?.({ line: event.content });
|
|
140
141
|
} else if (event.type === "status" && event.metadata?.exitCode !== void 0) {
|
|
141
142
|
exitCode = event.metadata.exitCode;
|
|
@@ -148,8 +149,24 @@ class Sandbox {
|
|
|
148
149
|
return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode };
|
|
149
150
|
}
|
|
150
151
|
// Lifecycle methods
|
|
152
|
+
// Retries on 409 (active runs) to handle eventual consistency between
|
|
153
|
+
// the SSE stream completion and the DB status update
|
|
151
154
|
async kill() {
|
|
152
|
-
|
|
155
|
+
const maxAttempts = 5;
|
|
156
|
+
const baseDelayMs = 500;
|
|
157
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
158
|
+
try {
|
|
159
|
+
await this.client.deleteSandbox(this.sandboxId);
|
|
160
|
+
return;
|
|
161
|
+
} catch (error) {
|
|
162
|
+
const isConflict = error instanceof FetchError && error.status === 409;
|
|
163
|
+
if (isConflict && attempt < maxAttempts) {
|
|
164
|
+
await new Promise((resolve) => setTimeout(resolve, baseDelayMs * attempt));
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
153
170
|
}
|
|
154
171
|
async betaPause() {
|
|
155
172
|
}
|
|
@@ -239,7 +256,7 @@ class SandboxClient {
|
|
|
239
256
|
if (!res.ok) {
|
|
240
257
|
throw await FetchError.from(url, options.method ?? "GET", res);
|
|
241
258
|
}
|
|
242
|
-
return res.json();
|
|
259
|
+
return await res.json();
|
|
243
260
|
}
|
|
244
261
|
// === Runs ===
|
|
245
262
|
async createRun(request) {
|
|
@@ -251,7 +268,7 @@ class SandboxClient {
|
|
|
251
268
|
}
|
|
252
269
|
async createRunAndWait(request) {
|
|
253
270
|
const run = await this.createRun(request);
|
|
254
|
-
return run.waitForCompletion();
|
|
271
|
+
return await run.waitForCompletion();
|
|
255
272
|
}
|
|
256
273
|
async *streamRun(request) {
|
|
257
274
|
const url = `${this.apiUrl}/api/runs/stream`;
|
|
@@ -269,7 +286,39 @@ class SandboxClient {
|
|
|
269
286
|
if (!res.ok) {
|
|
270
287
|
throw await FetchError.from(url, "POST", res);
|
|
271
288
|
}
|
|
272
|
-
|
|
289
|
+
let capturedRunId;
|
|
290
|
+
try {
|
|
291
|
+
for await (const event of parseSSEStream(res)) {
|
|
292
|
+
if (event.type === "run_created" && event.runId) {
|
|
293
|
+
capturedRunId = event.runId;
|
|
294
|
+
}
|
|
295
|
+
yield event;
|
|
296
|
+
}
|
|
297
|
+
} catch (error) {
|
|
298
|
+
if (!capturedRunId) {
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
let run = await this.getRun(capturedRunId);
|
|
302
|
+
if (!run.isComplete) {
|
|
303
|
+
run = await run.waitForCompletion();
|
|
304
|
+
}
|
|
305
|
+
if (run.stdout) {
|
|
306
|
+
yield { type: "stdout", content: run.stdout };
|
|
307
|
+
}
|
|
308
|
+
if (run.stderr) {
|
|
309
|
+
yield { type: "stderr", content: run.stderr };
|
|
310
|
+
}
|
|
311
|
+
yield {
|
|
312
|
+
type: "done",
|
|
313
|
+
runId: capturedRunId,
|
|
314
|
+
sandboxId: run.sandboxId,
|
|
315
|
+
metadata: {
|
|
316
|
+
exitCode: run.exitCode ?? 0,
|
|
317
|
+
durationMs: run.durationMs,
|
|
318
|
+
errorMessage: run.errorMessage
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
}
|
|
273
322
|
}
|
|
274
323
|
async getRun(runId) {
|
|
275
324
|
const response = await this.fetch(`/api/runs/${runId}`);
|
|
@@ -282,7 +331,7 @@ class SandboxClient {
|
|
|
282
331
|
body: JSON.stringify(request)
|
|
283
332
|
});
|
|
284
333
|
await pollUntilComplete(
|
|
285
|
-
() => this.getSandboxStatus(response.data.sandboxId),
|
|
334
|
+
async () => await this.getSandboxStatus(response.data.sandboxId),
|
|
286
335
|
{ intervalMs: 200, maxAttempts: 150 }
|
|
287
336
|
// 30s max
|
|
288
337
|
);
|
package/package.json
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
2
|
+
"name": "@meistrari/sandbox-sdk",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": {
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"import": "./dist/index.mjs",
|
|
9
|
+
"require": "./dist/index.cjs"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"main": "dist/index.mjs",
|
|
13
|
+
"types": "dist/index.d.ts",
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "unbuild",
|
|
19
|
+
"test": "vitest"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"eventsource-parser": "^3.0.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"unbuild": "^2.0.0",
|
|
26
|
+
"vitest": "^2.0.0",
|
|
27
|
+
"typescript": "^5.0.0"
|
|
10
28
|
}
|
|
11
|
-
},
|
|
12
|
-
"main": "dist/index.mjs",
|
|
13
|
-
"types": "dist/index.d.ts",
|
|
14
|
-
"files": [
|
|
15
|
-
"dist"
|
|
16
|
-
],
|
|
17
|
-
"scripts": {
|
|
18
|
-
"build": "unbuild",
|
|
19
|
-
"test": "vitest"
|
|
20
|
-
},
|
|
21
|
-
"dependencies": {
|
|
22
|
-
"eventsource-parser": "^3.0.0"
|
|
23
|
-
},
|
|
24
|
-
"devDependencies": {
|
|
25
|
-
"unbuild": "^2.0.0",
|
|
26
|
-
"vitest": "^2.0.0",
|
|
27
|
-
"typescript": "^5.0.0"
|
|
28
|
-
}
|
|
29
29
|
}
|