@cloudflare/sandbox 0.2.0 → 0.2.2

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 (59) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/Dockerfile +31 -7
  3. package/README.md +226 -2
  4. package/container_src/bun.lock +122 -0
  5. package/container_src/circuit-breaker.ts +121 -0
  6. package/container_src/index.ts +305 -10
  7. package/container_src/jupyter-server.ts +579 -0
  8. package/container_src/jupyter-service.ts +448 -0
  9. package/container_src/mime-processor.ts +255 -0
  10. package/container_src/package.json +9 -0
  11. package/container_src/startup.sh +83 -0
  12. package/dist/{chunk-YVZ3K26G.js → chunk-CUHYLCMT.js} +9 -21
  13. package/dist/chunk-CUHYLCMT.js.map +1 -0
  14. package/dist/chunk-EGC5IYXA.js +108 -0
  15. package/dist/chunk-EGC5IYXA.js.map +1 -0
  16. package/dist/chunk-FKBV7CZS.js +113 -0
  17. package/dist/chunk-FKBV7CZS.js.map +1 -0
  18. package/dist/chunk-LALY4SFU.js +129 -0
  19. package/dist/chunk-LALY4SFU.js.map +1 -0
  20. package/dist/{chunk-6THNBO4S.js → chunk-S5FFBU4Y.js} +1 -1
  21. package/dist/{chunk-6THNBO4S.js.map → chunk-S5FFBU4Y.js.map} +1 -1
  22. package/dist/chunk-VTKZL632.js +237 -0
  23. package/dist/chunk-VTKZL632.js.map +1 -0
  24. package/dist/{chunk-ZJN2PQOS.js → chunk-ZMPO44U4.js} +171 -72
  25. package/dist/chunk-ZMPO44U4.js.map +1 -0
  26. package/dist/{client-BXYlxy-j.d.ts → client-bzEV222a.d.ts} +52 -4
  27. package/dist/client.d.ts +2 -1
  28. package/dist/client.js +1 -1
  29. package/dist/errors.d.ts +95 -0
  30. package/dist/errors.js +27 -0
  31. package/dist/errors.js.map +1 -0
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +33 -3
  34. package/dist/interpreter-types.d.ts +259 -0
  35. package/dist/interpreter-types.js +9 -0
  36. package/dist/interpreter-types.js.map +1 -0
  37. package/dist/interpreter.d.ts +33 -0
  38. package/dist/interpreter.js +8 -0
  39. package/dist/interpreter.js.map +1 -0
  40. package/dist/jupyter-client.d.ts +4 -0
  41. package/dist/jupyter-client.js +9 -0
  42. package/dist/jupyter-client.js.map +1 -0
  43. package/dist/request-handler.d.ts +2 -1
  44. package/dist/request-handler.js +8 -3
  45. package/dist/sandbox.d.ts +2 -1
  46. package/dist/sandbox.js +8 -3
  47. package/dist/types.d.ts +8 -0
  48. package/dist/types.js +1 -1
  49. package/package.json +1 -1
  50. package/src/client.ts +37 -54
  51. package/src/errors.ts +218 -0
  52. package/src/index.ts +44 -10
  53. package/src/interpreter-types.ts +383 -0
  54. package/src/interpreter.ts +150 -0
  55. package/src/jupyter-client.ts +349 -0
  56. package/src/sandbox.ts +281 -153
  57. package/src/types.ts +15 -0
  58. package/dist/chunk-YVZ3K26G.js.map +0 -1
  59. package/dist/chunk-ZJN2PQOS.js.map +0 -1
package/src/client.ts CHANGED
@@ -6,7 +6,7 @@ import type {
6
6
  GetProcessResponse,
7
7
  ListProcessesResponse,
8
8
  StartProcessRequest,
9
- StartProcessResponse
9
+ StartProcessResponse,
10
10
  } from "./types";
11
11
 
12
12
  export interface ExecuteResponse {
@@ -18,22 +18,6 @@ export interface ExecuteResponse {
18
18
  timestamp: string;
19
19
  }
20
20
 
21
- interface SessionResponse {
22
- sessionId: string;
23
- message: string;
24
- timestamp: string;
25
- }
26
-
27
- interface SessionListResponse {
28
- sessions: Array<{
29
- sessionId: string;
30
- hasActiveProcess: boolean;
31
- createdAt: string;
32
- }>;
33
- count: number;
34
- timestamp: string;
35
- }
36
-
37
21
  interface CommandsResponse {
38
22
  availableCommands: string[];
39
23
  timestamp: string;
@@ -209,7 +193,7 @@ export class HttpClient {
209
193
  this.baseUrl = this.options.baseUrl!;
210
194
  }
211
195
 
212
- private async doFetch(
196
+ protected async doFetch(
213
197
  path: string,
214
198
  options?: RequestInit
215
199
  ): Promise<Response> {
@@ -252,7 +236,7 @@ export class HttpClient {
252
236
 
253
237
  async execute(
254
238
  command: string,
255
- options: Pick<BaseExecOptions, 'sessionId' | 'cwd' | 'env'>
239
+ options: Pick<BaseExecOptions, "sessionId" | "cwd" | "env">
256
240
  ): Promise<ExecuteResponse> {
257
241
  try {
258
242
  const targetSessionId = options.sessionId || this.sessionId;
@@ -305,7 +289,6 @@ export class HttpClient {
305
289
  }
306
290
  }
307
291
 
308
-
309
292
  async executeCommandStream(
310
293
  command: string,
311
294
  sessionId?: string
@@ -320,7 +303,7 @@ export class HttpClient {
320
303
  }),
321
304
  headers: {
322
305
  "Content-Type": "application/json",
323
- "Accept": "text/event-stream",
306
+ Accept: "text/event-stream",
324
307
  },
325
308
  method: "POST",
326
309
  });
@@ -338,9 +321,7 @@ export class HttpClient {
338
321
  throw new Error("No response body for streaming request");
339
322
  }
340
323
 
341
- console.log(
342
- `[HTTP Client] Started command stream: ${command}`
343
- );
324
+ console.log(`[HTTP Client] Started command stream: ${command}`);
344
325
 
345
326
  return response.body;
346
327
  } catch (error) {
@@ -392,7 +373,6 @@ export class HttpClient {
392
373
  }
393
374
  }
394
375
 
395
-
396
376
  async mkdir(
397
377
  path: string,
398
378
  recursive: boolean = false,
@@ -434,7 +414,6 @@ export class HttpClient {
434
414
  }
435
415
  }
436
416
 
437
-
438
417
  async writeFile(
439
418
  path: string,
440
419
  content: string,
@@ -478,7 +457,6 @@ export class HttpClient {
478
457
  }
479
458
  }
480
459
 
481
-
482
460
  async readFile(
483
461
  path: string,
484
462
  encoding: string = "utf-8",
@@ -520,7 +498,6 @@ export class HttpClient {
520
498
  }
521
499
  }
522
500
 
523
-
524
501
  async deleteFile(
525
502
  path: string,
526
503
  sessionId?: string
@@ -560,7 +537,6 @@ export class HttpClient {
560
537
  }
561
538
  }
562
539
 
563
-
564
540
  async renameFile(
565
541
  oldPath: string,
566
542
  newPath: string,
@@ -602,7 +578,6 @@ export class HttpClient {
602
578
  }
603
579
  }
604
580
 
605
-
606
581
  async moveFile(
607
582
  sourcePath: string,
608
583
  destinationPath: string,
@@ -644,7 +619,6 @@ export class HttpClient {
644
619
  }
645
620
  }
646
621
 
647
-
648
622
  async exposePort(port: number, name?: string): Promise<ExposePortResponse> {
649
623
  try {
650
624
  const response = await this.doFetch(`/api/expose-port`, {
@@ -670,7 +644,9 @@ export class HttpClient {
670
644
 
671
645
  const data: ExposePortResponse = await response.json();
672
646
  console.log(
673
- `[HTTP Client] Port exposed: ${port}${name ? ` (${name})` : ""}, Success: ${data.success}`
647
+ `[HTTP Client] Port exposed: ${port}${
648
+ name ? ` (${name})` : ""
649
+ }, Success: ${data.success}`
674
650
  );
675
651
 
676
652
  return data;
@@ -732,9 +708,7 @@ export class HttpClient {
732
708
  }
733
709
 
734
710
  const data: GetExposedPortsResponse = await response.json();
735
- console.log(
736
- `[HTTP Client] Got ${data.count} exposed ports`
737
- );
711
+ console.log(`[HTTP Client] Got ${data.count} exposed ports`);
738
712
 
739
713
  return data;
740
714
  } catch (error) {
@@ -871,9 +845,7 @@ export class HttpClient {
871
845
  }
872
846
 
873
847
  const data: ListProcessesResponse = await response.json();
874
- console.log(
875
- `[HTTP Client] Listed ${data.processes.length} processes`
876
- );
848
+ console.log(`[HTTP Client] Listed ${data.processes.length} processes`);
877
849
 
878
850
  return data;
879
851
  } catch (error) {
@@ -902,7 +874,9 @@ export class HttpClient {
902
874
 
903
875
  const data: GetProcessResponse = await response.json();
904
876
  console.log(
905
- `[HTTP Client] Got process ${processId}: ${data.process?.status || 'not found'}`
877
+ `[HTTP Client] Got process ${processId}: ${
878
+ data.process?.status || "not found"
879
+ }`
906
880
  );
907
881
 
908
882
  return data;
@@ -912,7 +886,9 @@ export class HttpClient {
912
886
  }
913
887
  }
914
888
 
915
- async killProcess(processId: string): Promise<{ success: boolean; message: string }> {
889
+ async killProcess(
890
+ processId: string
891
+ ): Promise<{ success: boolean; message: string }> {
916
892
  try {
917
893
  const response = await this.doFetch(`/api/process/${processId}`, {
918
894
  headers: {
@@ -930,10 +906,11 @@ export class HttpClient {
930
906
  );
931
907
  }
932
908
 
933
- const data = await response.json() as { success: boolean; message: string };
934
- console.log(
935
- `[HTTP Client] Killed process ${processId}`
936
- );
909
+ const data = (await response.json()) as {
910
+ success: boolean;
911
+ message: string;
912
+ };
913
+ console.log(`[HTTP Client] Killed process ${processId}`);
937
914
 
938
915
  return data;
939
916
  } catch (error) {
@@ -942,7 +919,11 @@ export class HttpClient {
942
919
  }
943
920
  }
944
921
 
945
- async killAllProcesses(): Promise<{ success: boolean; killedCount: number; message: string }> {
922
+ async killAllProcesses(): Promise<{
923
+ success: boolean;
924
+ killedCount: number;
925
+ message: string;
926
+ }> {
946
927
  try {
947
928
  const response = await this.doFetch("/api/process/kill-all", {
948
929
  headers: {
@@ -960,10 +941,12 @@ export class HttpClient {
960
941
  );
961
942
  }
962
943
 
963
- const data = await response.json() as { success: boolean; killedCount: number; message: string };
964
- console.log(
965
- `[HTTP Client] Killed ${data.killedCount} processes`
966
- );
944
+ const data = (await response.json()) as {
945
+ success: boolean;
946
+ killedCount: number;
947
+ message: string;
948
+ };
949
+ console.log(`[HTTP Client] Killed ${data.killedCount} processes`);
967
950
 
968
951
  return data;
969
952
  } catch (error) {
@@ -991,9 +974,7 @@ export class HttpClient {
991
974
  }
992
975
 
993
976
  const data: GetProcessLogsResponse = await response.json();
994
- console.log(
995
- `[HTTP Client] Got logs for process ${processId}`
996
- );
977
+ console.log(`[HTTP Client] Got logs for process ${processId}`);
997
978
 
998
979
  return data;
999
980
  } catch (error) {
@@ -1002,11 +983,13 @@ export class HttpClient {
1002
983
  }
1003
984
  }
1004
985
 
1005
- async streamProcessLogs(processId: string): Promise<ReadableStream<Uint8Array>> {
986
+ async streamProcessLogs(
987
+ processId: string
988
+ ): Promise<ReadableStream<Uint8Array>> {
1006
989
  try {
1007
990
  const response = await this.doFetch(`/api/process/${processId}/stream`, {
1008
991
  headers: {
1009
- "Accept": "text/event-stream",
992
+ Accept: "text/event-stream",
1010
993
  "Cache-Control": "no-cache",
1011
994
  },
1012
995
  method: "GET",
package/src/errors.ts ADDED
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Standard error response from the sandbox API
3
+ */
4
+ export interface SandboxErrorResponse {
5
+ error?: string;
6
+ status?: string;
7
+ progress?: number;
8
+ }
9
+
10
+ /**
11
+ * Base error class for all Sandbox-related errors
12
+ */
13
+ export class SandboxError extends Error {
14
+ constructor(message: string) {
15
+ super(message);
16
+ this.name = this.constructor.name;
17
+
18
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
19
+ if (Error.captureStackTrace) {
20
+ Error.captureStackTrace(this, this.constructor);
21
+ }
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Error thrown when Jupyter functionality is requested but the service is still initializing.
27
+ *
28
+ * Note: With the current implementation, requests wait for Jupyter to be ready.
29
+ * This error is only thrown when:
30
+ * 1. The request times out waiting for Jupyter (default: 30 seconds)
31
+ * 2. Jupyter initialization actually fails
32
+ *
33
+ * Most requests will succeed after a delay, not throw this error.
34
+ */
35
+ export class JupyterNotReadyError extends SandboxError {
36
+ public readonly code = "JUPYTER_NOT_READY";
37
+ public readonly retryAfter: number;
38
+ public readonly progress?: number;
39
+
40
+ constructor(
41
+ message?: string,
42
+ options?: { retryAfter?: number; progress?: number }
43
+ ) {
44
+ super(
45
+ message || "Jupyter is still initializing. Please retry in a few seconds."
46
+ );
47
+ this.retryAfter = options?.retryAfter || 5;
48
+ this.progress = options?.progress;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Error thrown when a context is not found
54
+ */
55
+ export class ContextNotFoundError extends SandboxError {
56
+ public readonly code = "CONTEXT_NOT_FOUND";
57
+ public readonly contextId: string;
58
+
59
+ constructor(contextId: string) {
60
+ super(`Context ${contextId} not found`);
61
+ this.contextId = contextId;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Error thrown when code execution fails
67
+ */
68
+ export class CodeExecutionError extends SandboxError {
69
+ public readonly code = "CODE_EXECUTION_ERROR";
70
+ public readonly executionError?: {
71
+ ename?: string;
72
+ evalue?: string;
73
+ traceback?: string[];
74
+ };
75
+
76
+ constructor(message: string, executionError?: any) {
77
+ super(message);
78
+ this.executionError = executionError;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Error thrown when the sandbox container is not ready
84
+ */
85
+ export class ContainerNotReadyError extends SandboxError {
86
+ public readonly code = "CONTAINER_NOT_READY";
87
+
88
+ constructor(message?: string) {
89
+ super(
90
+ message ||
91
+ "Container is not ready. Please wait for initialization to complete."
92
+ );
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Error thrown when a network request to the sandbox fails
98
+ */
99
+ export class SandboxNetworkError extends SandboxError {
100
+ public readonly code = "NETWORK_ERROR";
101
+ public readonly statusCode?: number;
102
+ public readonly statusText?: string;
103
+
104
+ constructor(message: string, statusCode?: number, statusText?: string) {
105
+ super(message);
106
+ this.statusCode = statusCode;
107
+ this.statusText = statusText;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Error thrown when service is temporarily unavailable (e.g., circuit breaker open)
113
+ */
114
+ export class ServiceUnavailableError extends SandboxError {
115
+ public readonly code = "SERVICE_UNAVAILABLE";
116
+ public readonly retryAfter?: number;
117
+
118
+ constructor(message?: string, retryAfter?: number) {
119
+ // Simple, user-friendly message without implementation details
120
+ super(message || "Service temporarily unavailable");
121
+ this.retryAfter = retryAfter;
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Type guard to check if an error is a JupyterNotReadyError
127
+ */
128
+ export function isJupyterNotReadyError(
129
+ error: unknown
130
+ ): error is JupyterNotReadyError {
131
+ return error instanceof JupyterNotReadyError;
132
+ }
133
+
134
+ /**
135
+ * Type guard to check if an error is any SandboxError
136
+ */
137
+ export function isSandboxError(error: unknown): error is SandboxError {
138
+ return error instanceof SandboxError;
139
+ }
140
+
141
+ /**
142
+ * Helper to determine if an error is retryable
143
+ */
144
+ export function isRetryableError(error: unknown): boolean {
145
+ if (
146
+ error instanceof JupyterNotReadyError ||
147
+ error instanceof ContainerNotReadyError ||
148
+ error instanceof ServiceUnavailableError
149
+ ) {
150
+ return true;
151
+ }
152
+
153
+ if (error instanceof SandboxNetworkError) {
154
+ // Retry on 502, 503, 504 (gateway/service unavailable errors)
155
+ return error.statusCode
156
+ ? [502, 503, 504].includes(error.statusCode)
157
+ : false;
158
+ }
159
+
160
+ return false;
161
+ }
162
+
163
+ /**
164
+ * Parse error response from the sandbox API and return appropriate error instance
165
+ */
166
+ export async function parseErrorResponse(
167
+ response: Response
168
+ ): Promise<SandboxError> {
169
+ let data: SandboxErrorResponse;
170
+
171
+ try {
172
+ data = (await response.json()) as SandboxErrorResponse;
173
+ } catch {
174
+ // If JSON parsing fails, return a generic network error
175
+ return new SandboxNetworkError(
176
+ `Request failed with status ${response.status}`,
177
+ response.status,
178
+ response.statusText
179
+ );
180
+ }
181
+
182
+ // Check for specific error types based on response
183
+ if (response.status === 503) {
184
+ // Circuit breaker error
185
+ if (data.status === "circuit_open") {
186
+ return new ServiceUnavailableError(
187
+ "Service temporarily unavailable",
188
+ parseInt(response.headers.get("Retry-After") || "30")
189
+ );
190
+ }
191
+
192
+ // Jupyter initialization error
193
+ if (data.status === "initializing") {
194
+ return new JupyterNotReadyError(data.error, {
195
+ retryAfter: parseInt(response.headers.get("Retry-After") || "5"),
196
+ progress: data.progress,
197
+ });
198
+ }
199
+ }
200
+
201
+ // Check for context not found
202
+ if (
203
+ response.status === 404 &&
204
+ data.error?.includes("Context") &&
205
+ data.error?.includes("not found")
206
+ ) {
207
+ const contextId =
208
+ data.error.match(/Context (\S+) not found/)?.[1] || "unknown";
209
+ return new ContextNotFoundError(contextId);
210
+ }
211
+
212
+ // Default network error
213
+ return new SandboxNetworkError(
214
+ data.error || `Request failed with status ${response.status}`,
215
+ response.status,
216
+ response.statusText
217
+ );
218
+ }
package/src/index.ts CHANGED
@@ -1,20 +1,54 @@
1
1
  // Export types from client
2
2
  export type {
3
- DeleteFileResponse, ExecuteResponse,
3
+ DeleteFileResponse,
4
+ ExecuteResponse,
4
5
  GitCheckoutResponse,
5
- MkdirResponse, MoveFileResponse,
6
- ReadFileResponse, RenameFileResponse, WriteFileResponse
6
+ MkdirResponse,
7
+ MoveFileResponse,
8
+ ReadFileResponse,
9
+ RenameFileResponse,
10
+ WriteFileResponse,
7
11
  } from "./client";
8
-
12
+ // Export errors
13
+ export {
14
+ CodeExecutionError,
15
+ ContainerNotReadyError,
16
+ ContextNotFoundError,
17
+ isJupyterNotReadyError,
18
+ isRetryableError,
19
+ isSandboxError,
20
+ JupyterNotReadyError,
21
+ parseErrorResponse,
22
+ SandboxError,
23
+ type SandboxErrorResponse,
24
+ SandboxNetworkError,
25
+ ServiceUnavailableError,
26
+ } from "./errors";
27
+ // Export code interpreter types
28
+ export type {
29
+ ChartData,
30
+ CodeContext,
31
+ CreateContextOptions,
32
+ Execution,
33
+ ExecutionError,
34
+ OutputMessage,
35
+ Result,
36
+ RunCodeOptions,
37
+ } from "./interpreter-types";
38
+ // Export the implementations
39
+ export { ResultImpl } from "./interpreter-types";
9
40
  // Re-export request handler utilities
10
41
  export {
11
- proxyToSandbox, type RouteInfo, type SandboxEnv
12
- } from './request-handler';
13
-
42
+ proxyToSandbox,
43
+ type RouteInfo,
44
+ type SandboxEnv,
45
+ } from "./request-handler";
14
46
  export { getSandbox, Sandbox } from "./sandbox";
15
-
16
47
  // Export SSE parser for converting ReadableStream to AsyncIterable
17
- export { asyncIterableToSSEStream, parseSSEStream, responseToAsyncIterable } from "./sse-parser";
18
-
48
+ export {
49
+ asyncIterableToSSEStream,
50
+ parseSSEStream,
51
+ responseToAsyncIterable,
52
+ } from "./sse-parser";
19
53
  // Export event types for streaming
20
54
  export type { ExecEvent, LogEvent } from "./types";