@meistrari/sandbox-sdk 0.1.4

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/dist/index.mjs ADDED
@@ -0,0 +1,374 @@
1
+ import { createParser } from 'eventsource-parser';
2
+
3
+ class FetchError extends Error {
4
+ constructor(message, url, method, status, response) {
5
+ super(message);
6
+ this.url = url;
7
+ this.method = method;
8
+ this.status = status;
9
+ this.response = response;
10
+ this.name = "FetchError";
11
+ }
12
+ static async from(url, method, res) {
13
+ let body;
14
+ try {
15
+ body = await res.json();
16
+ } catch {
17
+ body = await res.text();
18
+ }
19
+ const message = typeof body === "object" && body && "error" in body ? body.error : `Request failed with status ${res.status}`;
20
+ return new FetchError(message, url, method, res.status, body);
21
+ }
22
+ }
23
+
24
+ async function* parseSSEStream(response) {
25
+ const reader = response.body?.getReader();
26
+ if (!reader)
27
+ throw new Error("No response body");
28
+ const decoder = new TextDecoder();
29
+ const events = [];
30
+ const parser = createParser({
31
+ onEvent: (event) => {
32
+ if (event.data) {
33
+ try {
34
+ events.push(JSON.parse(event.data));
35
+ } catch {
36
+ }
37
+ }
38
+ }
39
+ });
40
+ while (true) {
41
+ const { done, value } = await reader.read();
42
+ if (done)
43
+ break;
44
+ parser.feed(decoder.decode(value, { stream: true }));
45
+ while (events.length > 0) {
46
+ yield events.shift();
47
+ }
48
+ }
49
+ }
50
+
51
+ const TERMINAL_STATUSES = ["completed", "failed", "timeout", "cancelled"];
52
+ async function pollUntilComplete(fetcher, options = {}) {
53
+ const { intervalMs = 500, maxAttempts = 600, onStatus } = options;
54
+ let attempts = 0;
55
+ while (attempts < maxAttempts) {
56
+ const result = await fetcher();
57
+ onStatus?.(result.status);
58
+ if (TERMINAL_STATUSES.includes(result.status)) {
59
+ return result;
60
+ }
61
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
62
+ attempts++;
63
+ }
64
+ throw new Error(`Polling timeout after ${maxAttempts} attempts`);
65
+ }
66
+
67
+ var __defProp$2 = Object.defineProperty;
68
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
69
+ var __publicField$2 = (obj, key, value) => {
70
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
71
+ return value;
72
+ };
73
+ class Sandbox {
74
+ constructor(client, sandboxId, auth) {
75
+ this.client = client;
76
+ this.auth = auth;
77
+ __publicField$2(this, "sandboxId");
78
+ __publicField$2(this, "files");
79
+ __publicField$2(this, "commands");
80
+ __publicField$2(this, "timeoutMs", 3e5);
81
+ this.sandboxId = sandboxId;
82
+ const readFile = (path, options) => {
83
+ return this.client.readFile(sandboxId, path, options);
84
+ };
85
+ this.files = {
86
+ write: (path, content) => this.client.writeFile(sandboxId, path, content),
87
+ 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
+ };
92
+ this.commands = {
93
+ run: async (command) => {
94
+ const result = await this.runCode(command, { language: "bash" });
95
+ return {
96
+ stdout: result.stdout,
97
+ stderr: result.stderr,
98
+ exitCode: result.exitCode
99
+ };
100
+ }
101
+ };
102
+ }
103
+ // Factory methods (static)
104
+ static async create(client, options = {}) {
105
+ return client.createSandbox(options);
106
+ }
107
+ static async connect(client, sandboxId) {
108
+ return client.connectToSandbox(sandboxId);
109
+ }
110
+ // Normalize language aliases ('ts' -> 'typescript', 'js' -> 'javascript')
111
+ normalizeLanguage(lang) {
112
+ if (lang === "ts")
113
+ return "typescript";
114
+ if (lang === "js")
115
+ return "javascript";
116
+ return lang ?? "typescript";
117
+ }
118
+ // Main execution method (compatible with E2B and agent-api)
119
+ async runCode(script, options = {}) {
120
+ let stdout = "";
121
+ let stderr = "";
122
+ let exitCode;
123
+ const stream = this.client.streamRun({
124
+ code: script,
125
+ sandboxId: this.sandboxId,
126
+ language: this.normalizeLanguage(options.language),
127
+ env: options.envs,
128
+ timeoutMs: options.timeoutMs ?? this.timeoutMs,
129
+ libraries: options.libraries,
130
+ files: options.files
131
+ });
132
+ for await (const event of stream) {
133
+ if (event.type === "stdout" && event.content) {
134
+ stdout += event.content + "\n";
135
+ await options.onStdout?.({ line: event.content });
136
+ } else if (event.type === "stderr" && event.content) {
137
+ stderr += event.content + "\n";
138
+ await options.onStderr?.({ line: event.content });
139
+ } else if (event.type === "status" && event.metadata?.exitCode !== void 0) {
140
+ exitCode = event.metadata.exitCode;
141
+ } else if (event.type === "error") {
142
+ const error = new Error(event.content ?? "Execution error");
143
+ options.onError?.(error);
144
+ return { stdout, stderr, exitCode, error: event.content };
145
+ }
146
+ }
147
+ return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode };
148
+ }
149
+ // Lifecycle methods
150
+ async kill() {
151
+ await this.client.deleteSandbox(this.sandboxId);
152
+ }
153
+ async betaPause() {
154
+ }
155
+ setTimeout(ms) {
156
+ this.timeoutMs = ms;
157
+ }
158
+ }
159
+
160
+ var __defProp$1 = Object.defineProperty;
161
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
162
+ var __publicField$1 = (obj, key, value) => {
163
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
164
+ return value;
165
+ };
166
+ class SandboxRun {
167
+ constructor(client, data) {
168
+ this.client = client;
169
+ __publicField$1(this, "id");
170
+ __publicField$1(this, "sandboxId");
171
+ __publicField$1(this, "status");
172
+ __publicField$1(this, "stdout");
173
+ __publicField$1(this, "stderr");
174
+ __publicField$1(this, "exitCode");
175
+ __publicField$1(this, "errorMessage");
176
+ __publicField$1(this, "durationMs");
177
+ this.id = data.id;
178
+ this.sandboxId = data.sandboxId;
179
+ this.status = data.status;
180
+ this.stdout = data.stdout;
181
+ this.stderr = data.stderr;
182
+ this.exitCode = data.exitCode;
183
+ this.errorMessage = data.errorMessage;
184
+ this.durationMs = data.durationMs;
185
+ }
186
+ async refresh() {
187
+ const run = await this.client.getRun(this.id);
188
+ this.status = run.status;
189
+ this.stdout = run.stdout;
190
+ this.stderr = run.stderr;
191
+ this.exitCode = run.exitCode;
192
+ this.errorMessage = run.errorMessage;
193
+ this.durationMs = run.durationMs;
194
+ return this;
195
+ }
196
+ async waitForCompletion(options) {
197
+ await pollUntilComplete(
198
+ async () => {
199
+ await this.refresh();
200
+ return this;
201
+ },
202
+ options
203
+ );
204
+ return this;
205
+ }
206
+ get isComplete() {
207
+ return ["completed", "failed", "timeout", "cancelled"].includes(this.status);
208
+ }
209
+ get isSuccess() {
210
+ return this.status === "completed" && this.exitCode === 0;
211
+ }
212
+ }
213
+
214
+ var __defProp = Object.defineProperty;
215
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
216
+ var __publicField = (obj, key, value) => {
217
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
218
+ return value;
219
+ };
220
+ class SandboxClient {
221
+ constructor(config) {
222
+ __publicField(this, "apiUrl");
223
+ __publicField(this, "auth");
224
+ __publicField(this, "timeout");
225
+ this.apiUrl = config.apiUrl.replace(/\/$/, "");
226
+ this.auth = config.auth;
227
+ this.timeout = config.timeout ?? 3e5;
228
+ }
229
+ async fetch(path, options = {}) {
230
+ const url = `${this.apiUrl}${path}`;
231
+ const headers = new Headers(options.headers);
232
+ const authHeaders = this.auth.getHeaders();
233
+ authHeaders.forEach((value, key) => {
234
+ headers.set(key, value);
235
+ });
236
+ headers.set("Content-Type", "application/json");
237
+ const res = await fetch(url, { ...options, headers });
238
+ if (!res.ok) {
239
+ throw await FetchError.from(url, options.method ?? "GET", res);
240
+ }
241
+ return res.json();
242
+ }
243
+ // === Runs ===
244
+ async createRun(request) {
245
+ const response = await this.fetch("/api/runs", {
246
+ method: "POST",
247
+ body: JSON.stringify(request)
248
+ });
249
+ return new SandboxRun(this, response.data);
250
+ }
251
+ async createRunAndWait(request) {
252
+ const run = await this.createRun(request);
253
+ return run.waitForCompletion();
254
+ }
255
+ async *streamRun(request) {
256
+ const url = `${this.apiUrl}/api/runs/stream`;
257
+ const headers = new Headers();
258
+ const authHeaders = this.auth.getHeaders();
259
+ authHeaders.forEach((value, key) => {
260
+ headers.set(key, value);
261
+ });
262
+ headers.set("Content-Type", "application/json");
263
+ const res = await fetch(url, {
264
+ method: "POST",
265
+ headers,
266
+ body: JSON.stringify(request)
267
+ });
268
+ if (!res.ok) {
269
+ throw await FetchError.from(url, "POST", res);
270
+ }
271
+ yield* parseSSEStream(res);
272
+ }
273
+ async getRun(runId) {
274
+ const response = await this.fetch(`/api/runs/${runId}`);
275
+ return new SandboxRun(this, response.data);
276
+ }
277
+ // === Sandboxes ===
278
+ async createSandbox(request = {}) {
279
+ const response = await this.fetch("/api/sandboxes", {
280
+ method: "POST",
281
+ body: JSON.stringify(request)
282
+ });
283
+ await pollUntilComplete(
284
+ () => this.getSandboxStatus(response.data.sandboxId),
285
+ { intervalMs: 200, maxAttempts: 150 }
286
+ // 30s max
287
+ );
288
+ return new Sandbox(this, response.data.sandboxId, this.auth);
289
+ }
290
+ async getSandboxStatus(sandboxId) {
291
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}`);
292
+ return response.data;
293
+ }
294
+ async connectToSandbox(sandboxId) {
295
+ await this.getSandboxStatus(sandboxId);
296
+ return new Sandbox(this, sandboxId, this.auth);
297
+ }
298
+ async deleteSandbox(sandboxId) {
299
+ await this.fetch(`/api/sandboxes/${sandboxId}`, { method: "DELETE" });
300
+ }
301
+ // === File Operations ===
302
+ async writeFile(sandboxId, path, content) {
303
+ const isBuffer = content instanceof Uint8Array;
304
+ await this.fetch(`/api/sandboxes/${sandboxId}/files`, {
305
+ method: "POST",
306
+ body: JSON.stringify({
307
+ name: path.split("/").pop(),
308
+ path,
309
+ content: isBuffer ? Buffer.from(content).toString("base64") : content,
310
+ encoding: isBuffer ? "base64" : "utf8"
311
+ })
312
+ });
313
+ }
314
+ async readFile(sandboxId, path, options) {
315
+ const response = await this.fetch(
316
+ `/api/sandboxes/${sandboxId}/files/${encodeURIComponent(path)}`
317
+ );
318
+ const { file } = response;
319
+ const format = options?.format ?? "text";
320
+ if (format === "blob") {
321
+ if (file.encoding === "base64") {
322
+ const bytes2 = Uint8Array.from(Buffer.from(file.content, "base64"));
323
+ return new Blob([bytes2]);
324
+ }
325
+ const bytes = Uint8Array.from(Buffer.from(file.content, "utf8"));
326
+ return new Blob([bytes]);
327
+ }
328
+ if (file.encoding === "base64") {
329
+ return Buffer.from(file.content, "base64").toString("utf8");
330
+ }
331
+ return file.content;
332
+ }
333
+ async fileExists(sandboxId, path) {
334
+ try {
335
+ await this.fetch(`/api/sandboxes/${sandboxId}/files/${encodeURIComponent(path)}`);
336
+ return true;
337
+ } catch (error) {
338
+ if (error instanceof FetchError && error.status === 404) {
339
+ return false;
340
+ }
341
+ throw error;
342
+ }
343
+ }
344
+ async listFiles(sandboxId, directory) {
345
+ const query = directory ? `?directory=${encodeURIComponent(directory)}` : "";
346
+ const response = await this.fetch(
347
+ `/api/sandboxes/${sandboxId}/files${query}`
348
+ );
349
+ return response.files;
350
+ }
351
+ async deleteFile(sandboxId, path) {
352
+ await this.fetch(`/api/sandboxes/${sandboxId}/files`, {
353
+ method: "DELETE",
354
+ body: JSON.stringify({ filePaths: [path] })
355
+ });
356
+ }
357
+ }
358
+
359
+ class DataTokenAuthStrategy {
360
+ constructor(dataToken) {
361
+ this.dataToken = dataToken;
362
+ }
363
+ getHeaders() {
364
+ return new Headers({
365
+ "x-data-token": this.dataToken
366
+ });
367
+ }
368
+ }
369
+
370
+ function sandbox(config) {
371
+ return new SandboxClient(config);
372
+ }
373
+
374
+ export { DataTokenAuthStrategy, FetchError, Sandbox, SandboxClient, SandboxRun, sandbox };
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@meistrari/sandbox-sdk",
3
+ "version": "0.1.4",
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"
28
+ }
29
+ }