@cloudflare/sandbox 0.3.7 → 0.4.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 (120) hide show
  1. package/.turbo/turbo-build.log +44 -0
  2. package/CHANGELOG.md +8 -10
  3. package/Dockerfile +82 -18
  4. package/README.md +89 -824
  5. package/dist/chunk-53JFOF7F.js +2352 -0
  6. package/dist/chunk-53JFOF7F.js.map +1 -0
  7. package/dist/chunk-BFVUNTP4.js +104 -0
  8. package/dist/chunk-BFVUNTP4.js.map +1 -0
  9. package/dist/{chunk-NNGBXDMY.js → chunk-EKSWCBCA.js} +3 -6
  10. package/dist/chunk-EKSWCBCA.js.map +1 -0
  11. package/dist/chunk-JXZMAU2C.js +559 -0
  12. package/dist/chunk-JXZMAU2C.js.map +1 -0
  13. package/dist/{chunk-6UAWTJ5S.js → chunk-Z532A7QC.js} +13 -20
  14. package/dist/{chunk-6UAWTJ5S.js.map → chunk-Z532A7QC.js.map} +1 -1
  15. package/dist/file-stream.d.ts +16 -38
  16. package/dist/file-stream.js +1 -2
  17. package/dist/index.d.ts +6 -5
  18. package/dist/index.js +45 -38
  19. package/dist/interpreter.d.ts +3 -3
  20. package/dist/interpreter.js +2 -2
  21. package/dist/request-handler.d.ts +4 -3
  22. package/dist/request-handler.js +4 -7
  23. package/dist/sandbox-D9K2ypln.d.ts +583 -0
  24. package/dist/sandbox.d.ts +3 -3
  25. package/dist/sandbox.js +4 -7
  26. package/dist/security.d.ts +4 -3
  27. package/dist/security.js +3 -3
  28. package/dist/sse-parser.js +1 -1
  29. package/package.json +12 -4
  30. package/src/clients/base-client.ts +280 -0
  31. package/src/clients/command-client.ts +115 -0
  32. package/src/clients/file-client.ts +269 -0
  33. package/src/clients/git-client.ts +92 -0
  34. package/src/clients/index.ts +63 -0
  35. package/src/{interpreter-client.ts → clients/interpreter-client.ts} +148 -171
  36. package/src/clients/port-client.ts +105 -0
  37. package/src/clients/process-client.ts +177 -0
  38. package/src/clients/sandbox-client.ts +41 -0
  39. package/src/clients/types.ts +84 -0
  40. package/src/clients/utility-client.ts +94 -0
  41. package/src/errors/adapter.ts +180 -0
  42. package/src/errors/classes.ts +469 -0
  43. package/src/errors/index.ts +105 -0
  44. package/src/file-stream.ts +119 -117
  45. package/src/index.ts +81 -69
  46. package/src/interpreter.ts +17 -8
  47. package/src/request-handler.ts +69 -43
  48. package/src/sandbox.ts +694 -533
  49. package/src/security.ts +14 -23
  50. package/src/sse-parser.ts +4 -8
  51. package/startup.sh +3 -0
  52. package/tests/base-client.test.ts +328 -0
  53. package/tests/command-client.test.ts +407 -0
  54. package/tests/file-client.test.ts +643 -0
  55. package/tests/file-stream.test.ts +306 -0
  56. package/tests/git-client.test.ts +328 -0
  57. package/tests/port-client.test.ts +301 -0
  58. package/tests/process-client.test.ts +658 -0
  59. package/tests/sandbox.test.ts +465 -0
  60. package/tests/sse-parser.test.ts +290 -0
  61. package/tests/utility-client.test.ts +266 -0
  62. package/tests/wrangler.jsonc +35 -0
  63. package/tsconfig.json +9 -1
  64. package/vitest.config.ts +31 -0
  65. package/container_src/bun.lock +0 -76
  66. package/container_src/circuit-breaker.ts +0 -121
  67. package/container_src/control-process.ts +0 -784
  68. package/container_src/handler/exec.ts +0 -185
  69. package/container_src/handler/file.ts +0 -457
  70. package/container_src/handler/git.ts +0 -130
  71. package/container_src/handler/ports.ts +0 -314
  72. package/container_src/handler/process.ts +0 -568
  73. package/container_src/handler/session.ts +0 -92
  74. package/container_src/index.ts +0 -601
  75. package/container_src/interpreter-service.ts +0 -276
  76. package/container_src/isolation.ts +0 -1213
  77. package/container_src/mime-processor.ts +0 -255
  78. package/container_src/package.json +0 -18
  79. package/container_src/runtime/executors/javascript/node_executor.ts +0 -123
  80. package/container_src/runtime/executors/python/ipython_executor.py +0 -338
  81. package/container_src/runtime/executors/typescript/ts_executor.ts +0 -138
  82. package/container_src/runtime/process-pool.ts +0 -464
  83. package/container_src/shell-escape.ts +0 -42
  84. package/container_src/startup.sh +0 -11
  85. package/container_src/types.ts +0 -131
  86. package/dist/chunk-32UDXUPC.js +0 -671
  87. package/dist/chunk-32UDXUPC.js.map +0 -1
  88. package/dist/chunk-5DILEXGY.js +0 -85
  89. package/dist/chunk-5DILEXGY.js.map +0 -1
  90. package/dist/chunk-D3U63BZP.js +0 -240
  91. package/dist/chunk-D3U63BZP.js.map +0 -1
  92. package/dist/chunk-FXYPFGOZ.js +0 -129
  93. package/dist/chunk-FXYPFGOZ.js.map +0 -1
  94. package/dist/chunk-JTKON2SH.js +0 -113
  95. package/dist/chunk-JTKON2SH.js.map +0 -1
  96. package/dist/chunk-NNGBXDMY.js.map +0 -1
  97. package/dist/chunk-SQLJNZ3K.js +0 -674
  98. package/dist/chunk-SQLJNZ3K.js.map +0 -1
  99. package/dist/chunk-W7TVRPBG.js +0 -108
  100. package/dist/chunk-W7TVRPBG.js.map +0 -1
  101. package/dist/client-B3RUab0s.d.ts +0 -225
  102. package/dist/client.d.ts +0 -4
  103. package/dist/client.js +0 -7
  104. package/dist/client.js.map +0 -1
  105. package/dist/errors.d.ts +0 -95
  106. package/dist/errors.js +0 -27
  107. package/dist/errors.js.map +0 -1
  108. package/dist/interpreter-client.d.ts +0 -4
  109. package/dist/interpreter-client.js +0 -9
  110. package/dist/interpreter-client.js.map +0 -1
  111. package/dist/interpreter-types.d.ts +0 -259
  112. package/dist/interpreter-types.js +0 -9
  113. package/dist/interpreter-types.js.map +0 -1
  114. package/dist/types.d.ts +0 -453
  115. package/dist/types.js +0 -45
  116. package/dist/types.js.map +0 -1
  117. package/src/client.ts +0 -1048
  118. package/src/errors.ts +0 -219
  119. package/src/interpreter-types.ts +0 -390
  120. package/src/types.ts +0 -571
@@ -0,0 +1,2352 @@
1
+ import {
2
+ CodeInterpreter,
3
+ ResultImpl,
4
+ TraceContext,
5
+ createLogger,
6
+ createNoOpLogger,
7
+ runWithLogger
8
+ } from "./chunk-JXZMAU2C.js";
9
+ import {
10
+ SecurityError,
11
+ sanitizeSandboxId,
12
+ validatePort
13
+ } from "./chunk-Z532A7QC.js";
14
+ import {
15
+ parseSSEStream
16
+ } from "./chunk-EKSWCBCA.js";
17
+
18
+ // src/sandbox.ts
19
+ import { Container, getContainer } from "@cloudflare/containers";
20
+
21
+ // ../shared/dist/errors/codes.js
22
+ var ErrorCode = {
23
+ // File System Errors (404)
24
+ FILE_NOT_FOUND: "FILE_NOT_FOUND",
25
+ // Permission Errors (403)
26
+ PERMISSION_DENIED: "PERMISSION_DENIED",
27
+ // File System Errors (409)
28
+ FILE_EXISTS: "FILE_EXISTS",
29
+ // File System Errors (400)
30
+ IS_DIRECTORY: "IS_DIRECTORY",
31
+ NOT_DIRECTORY: "NOT_DIRECTORY",
32
+ // File System Errors (500)
33
+ NO_SPACE: "NO_SPACE",
34
+ TOO_MANY_FILES: "TOO_MANY_FILES",
35
+ RESOURCE_BUSY: "RESOURCE_BUSY",
36
+ READ_ONLY: "READ_ONLY",
37
+ NAME_TOO_LONG: "NAME_TOO_LONG",
38
+ TOO_MANY_LINKS: "TOO_MANY_LINKS",
39
+ FILESYSTEM_ERROR: "FILESYSTEM_ERROR",
40
+ // Command Errors (404)
41
+ COMMAND_NOT_FOUND: "COMMAND_NOT_FOUND",
42
+ // Command Errors (403/400)
43
+ COMMAND_PERMISSION_DENIED: "COMMAND_PERMISSION_DENIED",
44
+ INVALID_COMMAND: "INVALID_COMMAND",
45
+ // Command Errors (500)
46
+ COMMAND_EXECUTION_ERROR: "COMMAND_EXECUTION_ERROR",
47
+ STREAM_START_ERROR: "STREAM_START_ERROR",
48
+ // Process Errors (404)
49
+ PROCESS_NOT_FOUND: "PROCESS_NOT_FOUND",
50
+ // Process Errors (403/500)
51
+ PROCESS_PERMISSION_DENIED: "PROCESS_PERMISSION_DENIED",
52
+ PROCESS_ERROR: "PROCESS_ERROR",
53
+ // Port Errors (409)
54
+ PORT_ALREADY_EXPOSED: "PORT_ALREADY_EXPOSED",
55
+ PORT_IN_USE: "PORT_IN_USE",
56
+ // Port Errors (404)
57
+ PORT_NOT_EXPOSED: "PORT_NOT_EXPOSED",
58
+ // Port Errors (400)
59
+ INVALID_PORT_NUMBER: "INVALID_PORT_NUMBER",
60
+ INVALID_PORT: "INVALID_PORT",
61
+ // Port Errors (502/500)
62
+ SERVICE_NOT_RESPONDING: "SERVICE_NOT_RESPONDING",
63
+ PORT_OPERATION_ERROR: "PORT_OPERATION_ERROR",
64
+ // Port Errors (400)
65
+ CUSTOM_DOMAIN_REQUIRED: "CUSTOM_DOMAIN_REQUIRED",
66
+ // Git Errors (404)
67
+ GIT_REPOSITORY_NOT_FOUND: "GIT_REPOSITORY_NOT_FOUND",
68
+ GIT_BRANCH_NOT_FOUND: "GIT_BRANCH_NOT_FOUND",
69
+ // Git Errors (401)
70
+ GIT_AUTH_FAILED: "GIT_AUTH_FAILED",
71
+ // Git Errors (502)
72
+ GIT_NETWORK_ERROR: "GIT_NETWORK_ERROR",
73
+ // Git Errors (400)
74
+ INVALID_GIT_URL: "INVALID_GIT_URL",
75
+ // Git Errors (500)
76
+ GIT_CLONE_FAILED: "GIT_CLONE_FAILED",
77
+ GIT_CHECKOUT_FAILED: "GIT_CHECKOUT_FAILED",
78
+ GIT_OPERATION_FAILED: "GIT_OPERATION_FAILED",
79
+ // Code Interpreter Errors (503)
80
+ INTERPRETER_NOT_READY: "INTERPRETER_NOT_READY",
81
+ // Code Interpreter Errors (404)
82
+ CONTEXT_NOT_FOUND: "CONTEXT_NOT_FOUND",
83
+ // Code Interpreter Errors (500)
84
+ CODE_EXECUTION_ERROR: "CODE_EXECUTION_ERROR",
85
+ // Validation Errors (400)
86
+ VALIDATION_FAILED: "VALIDATION_FAILED",
87
+ // Generic Errors (400/500)
88
+ INVALID_JSON_RESPONSE: "INVALID_JSON_RESPONSE",
89
+ UNKNOWN_ERROR: "UNKNOWN_ERROR",
90
+ INTERNAL_ERROR: "INTERNAL_ERROR"
91
+ };
92
+
93
+ // ../shared/dist/errors/status-map.js
94
+ var ERROR_STATUS_MAP = {
95
+ // 404 Not Found
96
+ [ErrorCode.FILE_NOT_FOUND]: 404,
97
+ [ErrorCode.COMMAND_NOT_FOUND]: 404,
98
+ [ErrorCode.PROCESS_NOT_FOUND]: 404,
99
+ [ErrorCode.PORT_NOT_EXPOSED]: 404,
100
+ [ErrorCode.GIT_REPOSITORY_NOT_FOUND]: 404,
101
+ [ErrorCode.GIT_BRANCH_NOT_FOUND]: 404,
102
+ [ErrorCode.CONTEXT_NOT_FOUND]: 404,
103
+ // 400 Bad Request
104
+ [ErrorCode.IS_DIRECTORY]: 400,
105
+ [ErrorCode.NOT_DIRECTORY]: 400,
106
+ [ErrorCode.INVALID_COMMAND]: 400,
107
+ [ErrorCode.INVALID_PORT_NUMBER]: 400,
108
+ [ErrorCode.INVALID_PORT]: 400,
109
+ [ErrorCode.INVALID_GIT_URL]: 400,
110
+ [ErrorCode.CUSTOM_DOMAIN_REQUIRED]: 400,
111
+ [ErrorCode.INVALID_JSON_RESPONSE]: 400,
112
+ [ErrorCode.NAME_TOO_LONG]: 400,
113
+ [ErrorCode.VALIDATION_FAILED]: 400,
114
+ // 401 Unauthorized
115
+ [ErrorCode.GIT_AUTH_FAILED]: 401,
116
+ // 403 Forbidden
117
+ [ErrorCode.PERMISSION_DENIED]: 403,
118
+ [ErrorCode.COMMAND_PERMISSION_DENIED]: 403,
119
+ [ErrorCode.PROCESS_PERMISSION_DENIED]: 403,
120
+ [ErrorCode.READ_ONLY]: 403,
121
+ // 409 Conflict
122
+ [ErrorCode.FILE_EXISTS]: 409,
123
+ [ErrorCode.PORT_ALREADY_EXPOSED]: 409,
124
+ [ErrorCode.PORT_IN_USE]: 409,
125
+ [ErrorCode.RESOURCE_BUSY]: 409,
126
+ // 502 Bad Gateway
127
+ [ErrorCode.SERVICE_NOT_RESPONDING]: 502,
128
+ [ErrorCode.GIT_NETWORK_ERROR]: 502,
129
+ // 503 Service Unavailable
130
+ [ErrorCode.INTERPRETER_NOT_READY]: 503,
131
+ // 500 Internal Server Error
132
+ [ErrorCode.NO_SPACE]: 500,
133
+ [ErrorCode.TOO_MANY_FILES]: 500,
134
+ [ErrorCode.TOO_MANY_LINKS]: 500,
135
+ [ErrorCode.FILESYSTEM_ERROR]: 500,
136
+ [ErrorCode.COMMAND_EXECUTION_ERROR]: 500,
137
+ [ErrorCode.STREAM_START_ERROR]: 500,
138
+ [ErrorCode.PROCESS_ERROR]: 500,
139
+ [ErrorCode.PORT_OPERATION_ERROR]: 500,
140
+ [ErrorCode.GIT_CLONE_FAILED]: 500,
141
+ [ErrorCode.GIT_CHECKOUT_FAILED]: 500,
142
+ [ErrorCode.GIT_OPERATION_FAILED]: 500,
143
+ [ErrorCode.CODE_EXECUTION_ERROR]: 500,
144
+ [ErrorCode.UNKNOWN_ERROR]: 500,
145
+ [ErrorCode.INTERNAL_ERROR]: 500
146
+ };
147
+
148
+ // src/errors/classes.ts
149
+ var SandboxError = class extends Error {
150
+ constructor(errorResponse) {
151
+ super(errorResponse.message);
152
+ this.errorResponse = errorResponse;
153
+ this.name = "SandboxError";
154
+ }
155
+ // Convenience accessors
156
+ get code() {
157
+ return this.errorResponse.code;
158
+ }
159
+ get context() {
160
+ return this.errorResponse.context;
161
+ }
162
+ get httpStatus() {
163
+ return this.errorResponse.httpStatus;
164
+ }
165
+ get operation() {
166
+ return this.errorResponse.operation;
167
+ }
168
+ get suggestion() {
169
+ return this.errorResponse.suggestion;
170
+ }
171
+ get timestamp() {
172
+ return this.errorResponse.timestamp;
173
+ }
174
+ get documentation() {
175
+ return this.errorResponse.documentation;
176
+ }
177
+ // Custom serialization for logging
178
+ toJSON() {
179
+ return {
180
+ name: this.name,
181
+ message: this.message,
182
+ code: this.code,
183
+ context: this.context,
184
+ httpStatus: this.httpStatus,
185
+ operation: this.operation,
186
+ suggestion: this.suggestion,
187
+ timestamp: this.timestamp,
188
+ documentation: this.documentation,
189
+ stack: this.stack
190
+ };
191
+ }
192
+ };
193
+ var FileNotFoundError = class extends SandboxError {
194
+ constructor(errorResponse) {
195
+ super(errorResponse);
196
+ this.name = "FileNotFoundError";
197
+ }
198
+ // Type-safe accessors
199
+ get path() {
200
+ return this.context.path;
201
+ }
202
+ };
203
+ var FileExistsError = class extends SandboxError {
204
+ constructor(errorResponse) {
205
+ super(errorResponse);
206
+ this.name = "FileExistsError";
207
+ }
208
+ // Type-safe accessor
209
+ get path() {
210
+ return this.context.path;
211
+ }
212
+ };
213
+ var FileSystemError = class extends SandboxError {
214
+ constructor(errorResponse) {
215
+ super(errorResponse);
216
+ this.name = "FileSystemError";
217
+ }
218
+ // Type-safe accessors
219
+ get path() {
220
+ return this.context.path;
221
+ }
222
+ get stderr() {
223
+ return this.context.stderr;
224
+ }
225
+ get exitCode() {
226
+ return this.context.exitCode;
227
+ }
228
+ };
229
+ var PermissionDeniedError = class extends SandboxError {
230
+ constructor(errorResponse) {
231
+ super(errorResponse);
232
+ this.name = "PermissionDeniedError";
233
+ }
234
+ get path() {
235
+ return this.context.path;
236
+ }
237
+ };
238
+ var CommandNotFoundError = class extends SandboxError {
239
+ constructor(errorResponse) {
240
+ super(errorResponse);
241
+ this.name = "CommandNotFoundError";
242
+ }
243
+ // Type-safe accessor
244
+ get command() {
245
+ return this.context.command;
246
+ }
247
+ };
248
+ var CommandError = class extends SandboxError {
249
+ constructor(errorResponse) {
250
+ super(errorResponse);
251
+ this.name = "CommandError";
252
+ }
253
+ // Type-safe accessors
254
+ get command() {
255
+ return this.context.command;
256
+ }
257
+ get exitCode() {
258
+ return this.context.exitCode;
259
+ }
260
+ get stdout() {
261
+ return this.context.stdout;
262
+ }
263
+ get stderr() {
264
+ return this.context.stderr;
265
+ }
266
+ };
267
+ var ProcessNotFoundError = class extends SandboxError {
268
+ constructor(errorResponse) {
269
+ super(errorResponse);
270
+ this.name = "ProcessNotFoundError";
271
+ }
272
+ // Type-safe accessor
273
+ get processId() {
274
+ return this.context.processId;
275
+ }
276
+ };
277
+ var ProcessError = class extends SandboxError {
278
+ constructor(errorResponse) {
279
+ super(errorResponse);
280
+ this.name = "ProcessError";
281
+ }
282
+ // Type-safe accessors
283
+ get processId() {
284
+ return this.context.processId;
285
+ }
286
+ get pid() {
287
+ return this.context.pid;
288
+ }
289
+ get exitCode() {
290
+ return this.context.exitCode;
291
+ }
292
+ get stderr() {
293
+ return this.context.stderr;
294
+ }
295
+ };
296
+ var PortAlreadyExposedError = class extends SandboxError {
297
+ constructor(errorResponse) {
298
+ super(errorResponse);
299
+ this.name = "PortAlreadyExposedError";
300
+ }
301
+ // Type-safe accessors
302
+ get port() {
303
+ return this.context.port;
304
+ }
305
+ get portName() {
306
+ return this.context.portName;
307
+ }
308
+ };
309
+ var PortNotExposedError = class extends SandboxError {
310
+ constructor(errorResponse) {
311
+ super(errorResponse);
312
+ this.name = "PortNotExposedError";
313
+ }
314
+ // Type-safe accessor
315
+ get port() {
316
+ return this.context.port;
317
+ }
318
+ };
319
+ var InvalidPortError = class extends SandboxError {
320
+ constructor(errorResponse) {
321
+ super(errorResponse);
322
+ this.name = "InvalidPortError";
323
+ }
324
+ // Type-safe accessors
325
+ get port() {
326
+ return this.context.port;
327
+ }
328
+ get reason() {
329
+ return this.context.reason;
330
+ }
331
+ };
332
+ var ServiceNotRespondingError = class extends SandboxError {
333
+ constructor(errorResponse) {
334
+ super(errorResponse);
335
+ this.name = "ServiceNotRespondingError";
336
+ }
337
+ // Type-safe accessors
338
+ get port() {
339
+ return this.context.port;
340
+ }
341
+ get portName() {
342
+ return this.context.portName;
343
+ }
344
+ };
345
+ var PortInUseError = class extends SandboxError {
346
+ constructor(errorResponse) {
347
+ super(errorResponse);
348
+ this.name = "PortInUseError";
349
+ }
350
+ // Type-safe accessor
351
+ get port() {
352
+ return this.context.port;
353
+ }
354
+ };
355
+ var PortError = class extends SandboxError {
356
+ constructor(errorResponse) {
357
+ super(errorResponse);
358
+ this.name = "PortError";
359
+ }
360
+ // Type-safe accessors
361
+ get port() {
362
+ return this.context.port;
363
+ }
364
+ get portName() {
365
+ return this.context.portName;
366
+ }
367
+ get stderr() {
368
+ return this.context.stderr;
369
+ }
370
+ };
371
+ var CustomDomainRequiredError = class extends SandboxError {
372
+ constructor(errorResponse) {
373
+ super(errorResponse);
374
+ this.name = "CustomDomainRequiredError";
375
+ }
376
+ };
377
+ var GitRepositoryNotFoundError = class extends SandboxError {
378
+ constructor(errorResponse) {
379
+ super(errorResponse);
380
+ this.name = "GitRepositoryNotFoundError";
381
+ }
382
+ // Type-safe accessor
383
+ get repository() {
384
+ return this.context.repository;
385
+ }
386
+ };
387
+ var GitAuthenticationError = class extends SandboxError {
388
+ constructor(errorResponse) {
389
+ super(errorResponse);
390
+ this.name = "GitAuthenticationError";
391
+ }
392
+ // Type-safe accessor
393
+ get repository() {
394
+ return this.context.repository;
395
+ }
396
+ };
397
+ var GitBranchNotFoundError = class extends SandboxError {
398
+ constructor(errorResponse) {
399
+ super(errorResponse);
400
+ this.name = "GitBranchNotFoundError";
401
+ }
402
+ // Type-safe accessors
403
+ get branch() {
404
+ return this.context.branch;
405
+ }
406
+ get repository() {
407
+ return this.context.repository;
408
+ }
409
+ };
410
+ var GitNetworkError = class extends SandboxError {
411
+ constructor(errorResponse) {
412
+ super(errorResponse);
413
+ this.name = "GitNetworkError";
414
+ }
415
+ // Type-safe accessors
416
+ get repository() {
417
+ return this.context.repository;
418
+ }
419
+ get branch() {
420
+ return this.context.branch;
421
+ }
422
+ get targetDir() {
423
+ return this.context.targetDir;
424
+ }
425
+ };
426
+ var GitCloneError = class extends SandboxError {
427
+ constructor(errorResponse) {
428
+ super(errorResponse);
429
+ this.name = "GitCloneError";
430
+ }
431
+ // Type-safe accessors
432
+ get repository() {
433
+ return this.context.repository;
434
+ }
435
+ get targetDir() {
436
+ return this.context.targetDir;
437
+ }
438
+ get stderr() {
439
+ return this.context.stderr;
440
+ }
441
+ get exitCode() {
442
+ return this.context.exitCode;
443
+ }
444
+ };
445
+ var GitCheckoutError = class extends SandboxError {
446
+ constructor(errorResponse) {
447
+ super(errorResponse);
448
+ this.name = "GitCheckoutError";
449
+ }
450
+ // Type-safe accessors
451
+ get branch() {
452
+ return this.context.branch;
453
+ }
454
+ get repository() {
455
+ return this.context.repository;
456
+ }
457
+ get stderr() {
458
+ return this.context.stderr;
459
+ }
460
+ };
461
+ var InvalidGitUrlError = class extends SandboxError {
462
+ constructor(errorResponse) {
463
+ super(errorResponse);
464
+ this.name = "InvalidGitUrlError";
465
+ }
466
+ // Type-safe accessor
467
+ get validationErrors() {
468
+ return this.context.validationErrors;
469
+ }
470
+ };
471
+ var GitError = class extends SandboxError {
472
+ constructor(errorResponse) {
473
+ super(errorResponse);
474
+ this.name = "GitError";
475
+ }
476
+ // Type-safe accessors
477
+ get repository() {
478
+ return this.context.repository;
479
+ }
480
+ get branch() {
481
+ return this.context.branch;
482
+ }
483
+ get targetDir() {
484
+ return this.context.targetDir;
485
+ }
486
+ get stderr() {
487
+ return this.context.stderr;
488
+ }
489
+ get exitCode() {
490
+ return this.context.exitCode;
491
+ }
492
+ };
493
+ var InterpreterNotReadyError = class extends SandboxError {
494
+ constructor(errorResponse) {
495
+ super(errorResponse);
496
+ this.name = "InterpreterNotReadyError";
497
+ }
498
+ // Type-safe accessors
499
+ get retryAfter() {
500
+ return this.context.retryAfter;
501
+ }
502
+ get progress() {
503
+ return this.context.progress;
504
+ }
505
+ };
506
+ var ContextNotFoundError = class extends SandboxError {
507
+ constructor(errorResponse) {
508
+ super(errorResponse);
509
+ this.name = "ContextNotFoundError";
510
+ }
511
+ // Type-safe accessor
512
+ get contextId() {
513
+ return this.context.contextId;
514
+ }
515
+ };
516
+ var CodeExecutionError = class extends SandboxError {
517
+ constructor(errorResponse) {
518
+ super(errorResponse);
519
+ this.name = "CodeExecutionError";
520
+ }
521
+ // Type-safe accessors
522
+ get contextId() {
523
+ return this.context.contextId;
524
+ }
525
+ get ename() {
526
+ return this.context.ename;
527
+ }
528
+ get evalue() {
529
+ return this.context.evalue;
530
+ }
531
+ get traceback() {
532
+ return this.context.traceback;
533
+ }
534
+ };
535
+ var ValidationFailedError = class extends SandboxError {
536
+ constructor(errorResponse) {
537
+ super(errorResponse);
538
+ this.name = "ValidationFailedError";
539
+ }
540
+ // Type-safe accessor
541
+ get validationErrors() {
542
+ return this.context.validationErrors;
543
+ }
544
+ };
545
+
546
+ // src/errors/adapter.ts
547
+ function createErrorFromResponse(errorResponse) {
548
+ switch (errorResponse.code) {
549
+ // File System Errors
550
+ case ErrorCode.FILE_NOT_FOUND:
551
+ return new FileNotFoundError(errorResponse);
552
+ case ErrorCode.FILE_EXISTS:
553
+ return new FileExistsError(errorResponse);
554
+ case ErrorCode.PERMISSION_DENIED:
555
+ return new PermissionDeniedError(errorResponse);
556
+ case ErrorCode.IS_DIRECTORY:
557
+ case ErrorCode.NOT_DIRECTORY:
558
+ case ErrorCode.NO_SPACE:
559
+ case ErrorCode.TOO_MANY_FILES:
560
+ case ErrorCode.RESOURCE_BUSY:
561
+ case ErrorCode.READ_ONLY:
562
+ case ErrorCode.NAME_TOO_LONG:
563
+ case ErrorCode.TOO_MANY_LINKS:
564
+ case ErrorCode.FILESYSTEM_ERROR:
565
+ return new FileSystemError(errorResponse);
566
+ // Command Errors
567
+ case ErrorCode.COMMAND_NOT_FOUND:
568
+ return new CommandNotFoundError(errorResponse);
569
+ case ErrorCode.COMMAND_PERMISSION_DENIED:
570
+ case ErrorCode.COMMAND_EXECUTION_ERROR:
571
+ case ErrorCode.INVALID_COMMAND:
572
+ case ErrorCode.STREAM_START_ERROR:
573
+ return new CommandError(errorResponse);
574
+ // Process Errors
575
+ case ErrorCode.PROCESS_NOT_FOUND:
576
+ return new ProcessNotFoundError(errorResponse);
577
+ case ErrorCode.PROCESS_PERMISSION_DENIED:
578
+ case ErrorCode.PROCESS_ERROR:
579
+ return new ProcessError(errorResponse);
580
+ // Port Errors
581
+ case ErrorCode.PORT_ALREADY_EXPOSED:
582
+ return new PortAlreadyExposedError(errorResponse);
583
+ case ErrorCode.PORT_NOT_EXPOSED:
584
+ return new PortNotExposedError(errorResponse);
585
+ case ErrorCode.INVALID_PORT_NUMBER:
586
+ case ErrorCode.INVALID_PORT:
587
+ return new InvalidPortError(errorResponse);
588
+ case ErrorCode.SERVICE_NOT_RESPONDING:
589
+ return new ServiceNotRespondingError(errorResponse);
590
+ case ErrorCode.PORT_IN_USE:
591
+ return new PortInUseError(errorResponse);
592
+ case ErrorCode.PORT_OPERATION_ERROR:
593
+ return new PortError(errorResponse);
594
+ case ErrorCode.CUSTOM_DOMAIN_REQUIRED:
595
+ return new CustomDomainRequiredError(errorResponse);
596
+ // Git Errors
597
+ case ErrorCode.GIT_REPOSITORY_NOT_FOUND:
598
+ return new GitRepositoryNotFoundError(errorResponse);
599
+ case ErrorCode.GIT_AUTH_FAILED:
600
+ return new GitAuthenticationError(errorResponse);
601
+ case ErrorCode.GIT_BRANCH_NOT_FOUND:
602
+ return new GitBranchNotFoundError(errorResponse);
603
+ case ErrorCode.GIT_NETWORK_ERROR:
604
+ return new GitNetworkError(errorResponse);
605
+ case ErrorCode.GIT_CLONE_FAILED:
606
+ return new GitCloneError(errorResponse);
607
+ case ErrorCode.GIT_CHECKOUT_FAILED:
608
+ return new GitCheckoutError(errorResponse);
609
+ case ErrorCode.INVALID_GIT_URL:
610
+ return new InvalidGitUrlError(errorResponse);
611
+ case ErrorCode.GIT_OPERATION_FAILED:
612
+ return new GitError(errorResponse);
613
+ // Code Interpreter Errors
614
+ case ErrorCode.INTERPRETER_NOT_READY:
615
+ return new InterpreterNotReadyError(errorResponse);
616
+ case ErrorCode.CONTEXT_NOT_FOUND:
617
+ return new ContextNotFoundError(errorResponse);
618
+ case ErrorCode.CODE_EXECUTION_ERROR:
619
+ return new CodeExecutionError(errorResponse);
620
+ // Validation Errors
621
+ case ErrorCode.VALIDATION_FAILED:
622
+ return new ValidationFailedError(errorResponse);
623
+ // Generic Errors
624
+ case ErrorCode.INVALID_JSON_RESPONSE:
625
+ case ErrorCode.UNKNOWN_ERROR:
626
+ case ErrorCode.INTERNAL_ERROR:
627
+ return new SandboxError(errorResponse);
628
+ default:
629
+ return new SandboxError(errorResponse);
630
+ }
631
+ }
632
+
633
+ // src/clients/base-client.ts
634
+ var TIMEOUT_MS = 6e4;
635
+ var MIN_TIME_FOR_RETRY_MS = 1e4;
636
+ var BaseHttpClient = class {
637
+ baseUrl;
638
+ options;
639
+ logger;
640
+ constructor(options = {}) {
641
+ this.options = options;
642
+ this.logger = options.logger ?? createNoOpLogger();
643
+ this.baseUrl = this.options.baseUrl;
644
+ }
645
+ /**
646
+ * Core HTTP request method with automatic retry for container provisioning delays
647
+ */
648
+ async doFetch(path, options) {
649
+ const startTime = Date.now();
650
+ let attempt = 0;
651
+ while (true) {
652
+ const response = await this.executeFetch(path, options);
653
+ if (response.status === 503) {
654
+ const isContainerProvisioning = await this.isContainerProvisioningError(response);
655
+ if (isContainerProvisioning) {
656
+ const elapsed = Date.now() - startTime;
657
+ const remaining = TIMEOUT_MS - elapsed;
658
+ if (remaining > MIN_TIME_FOR_RETRY_MS) {
659
+ const delay = Math.min(2e3 * 2 ** attempt, 16e3);
660
+ this.logger.info("Container provisioning in progress, retrying", {
661
+ attempt: attempt + 1,
662
+ delayMs: delay,
663
+ remainingSec: Math.floor(remaining / 1e3)
664
+ });
665
+ await new Promise((resolve) => setTimeout(resolve, delay));
666
+ attempt++;
667
+ continue;
668
+ } else {
669
+ this.logger.error("Container failed to provision after multiple attempts", new Error(`Failed after ${attempt + 1} attempts over 60s`));
670
+ return response;
671
+ }
672
+ }
673
+ }
674
+ return response;
675
+ }
676
+ }
677
+ /**
678
+ * Make a POST request with JSON body
679
+ */
680
+ async post(endpoint, data, responseHandler) {
681
+ const response = await this.doFetch(endpoint, {
682
+ method: "POST",
683
+ headers: {
684
+ "Content-Type": "application/json"
685
+ },
686
+ body: JSON.stringify(data)
687
+ });
688
+ return this.handleResponse(response, responseHandler);
689
+ }
690
+ /**
691
+ * Make a GET request
692
+ */
693
+ async get(endpoint, responseHandler) {
694
+ const response = await this.doFetch(endpoint, {
695
+ method: "GET"
696
+ });
697
+ return this.handleResponse(response, responseHandler);
698
+ }
699
+ /**
700
+ * Make a DELETE request
701
+ */
702
+ async delete(endpoint, responseHandler) {
703
+ const response = await this.doFetch(endpoint, {
704
+ method: "DELETE"
705
+ });
706
+ return this.handleResponse(response, responseHandler);
707
+ }
708
+ /**
709
+ * Handle HTTP response with error checking and parsing
710
+ */
711
+ async handleResponse(response, customHandler) {
712
+ if (!response.ok) {
713
+ await this.handleErrorResponse(response);
714
+ }
715
+ if (customHandler) {
716
+ return customHandler(response);
717
+ }
718
+ try {
719
+ return await response.json();
720
+ } catch (error) {
721
+ const errorResponse = {
722
+ code: ErrorCode.INVALID_JSON_RESPONSE,
723
+ message: `Invalid JSON response: ${error instanceof Error ? error.message : "Unknown parsing error"}`,
724
+ context: {},
725
+ httpStatus: response.status,
726
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
727
+ };
728
+ throw createErrorFromResponse(errorResponse);
729
+ }
730
+ }
731
+ /**
732
+ * Handle error responses with consistent error throwing
733
+ */
734
+ async handleErrorResponse(response) {
735
+ let errorData;
736
+ try {
737
+ errorData = await response.json();
738
+ } catch {
739
+ errorData = {
740
+ code: ErrorCode.INTERNAL_ERROR,
741
+ message: `HTTP error! status: ${response.status}`,
742
+ context: { statusText: response.statusText },
743
+ httpStatus: response.status,
744
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
745
+ };
746
+ }
747
+ const error = createErrorFromResponse(errorData);
748
+ this.options.onError?.(errorData.message, void 0);
749
+ throw error;
750
+ }
751
+ /**
752
+ * Create a streaming response handler for Server-Sent Events
753
+ */
754
+ async handleStreamResponse(response) {
755
+ if (!response.ok) {
756
+ await this.handleErrorResponse(response);
757
+ }
758
+ if (!response.body) {
759
+ throw new Error("No response body for streaming");
760
+ }
761
+ return response.body;
762
+ }
763
+ /**
764
+ * Utility method to log successful operations
765
+ */
766
+ logSuccess(operation, details) {
767
+ this.logger.info(`${operation} completed successfully`, details ? { details } : void 0);
768
+ }
769
+ /**
770
+ * Utility method to log errors intelligently
771
+ * Only logs unexpected errors (5xx), not expected errors (4xx)
772
+ *
773
+ * - 4xx errors (validation, not found, conflicts): Don't log (expected client errors)
774
+ * - 5xx errors (server failures, internal errors): DO log (unexpected server errors)
775
+ */
776
+ logError(operation, error) {
777
+ if (error && typeof error === "object" && "httpStatus" in error) {
778
+ const httpStatus = error.httpStatus;
779
+ if (httpStatus >= 500) {
780
+ this.logger.error(
781
+ `Unexpected error in ${operation}`,
782
+ error instanceof Error ? error : new Error(String(error)),
783
+ { httpStatus }
784
+ );
785
+ }
786
+ } else {
787
+ this.logger.error(
788
+ `Error in ${operation}`,
789
+ error instanceof Error ? error : new Error(String(error))
790
+ );
791
+ }
792
+ }
793
+ /**
794
+ * Check if 503 response is from container provisioning (retryable)
795
+ * vs user application (not retryable)
796
+ */
797
+ async isContainerProvisioningError(response) {
798
+ try {
799
+ const cloned = response.clone();
800
+ const text = await cloned.text();
801
+ return text.includes("There is no Container instance available");
802
+ } catch (error) {
803
+ this.logger.error("Error checking response body", error instanceof Error ? error : new Error(String(error)));
804
+ return false;
805
+ }
806
+ }
807
+ async executeFetch(path, options) {
808
+ const url = this.options.stub ? `http://localhost:${this.options.port}${path}` : `${this.baseUrl}${path}`;
809
+ try {
810
+ if (this.options.stub) {
811
+ return await this.options.stub.containerFetch(
812
+ url,
813
+ options || {},
814
+ this.options.port
815
+ );
816
+ } else {
817
+ return await fetch(url, options);
818
+ }
819
+ } catch (error) {
820
+ this.logger.error("HTTP request error", error instanceof Error ? error : new Error(String(error)), { method: options?.method || "GET", url });
821
+ throw error;
822
+ }
823
+ }
824
+ };
825
+
826
+ // src/clients/command-client.ts
827
+ var CommandClient = class extends BaseHttpClient {
828
+ /**
829
+ * Execute a command and return the complete result
830
+ * @param command - The command to execute
831
+ * @param sessionId - The session ID for this command execution
832
+ * @param timeoutMs - Optional timeout in milliseconds (unlimited by default)
833
+ */
834
+ async execute(command, sessionId, timeoutMs) {
835
+ try {
836
+ const data = {
837
+ command,
838
+ sessionId,
839
+ ...timeoutMs !== void 0 && { timeoutMs }
840
+ };
841
+ const response = await this.post(
842
+ "/api/execute",
843
+ data
844
+ );
845
+ this.logSuccess(
846
+ "Command executed",
847
+ `${command}, Success: ${response.success}`
848
+ );
849
+ this.options.onCommandComplete?.(
850
+ response.success,
851
+ response.exitCode,
852
+ response.stdout,
853
+ response.stderr,
854
+ response.command
855
+ );
856
+ return response;
857
+ } catch (error) {
858
+ this.logError("execute", error);
859
+ this.options.onError?.(
860
+ error instanceof Error ? error.message : String(error),
861
+ command
862
+ );
863
+ throw error;
864
+ }
865
+ }
866
+ /**
867
+ * Execute a command and return a stream of events
868
+ * @param command - The command to execute
869
+ * @param sessionId - The session ID for this command execution
870
+ */
871
+ async executeStream(command, sessionId) {
872
+ try {
873
+ const data = { command, sessionId };
874
+ const response = await this.doFetch("/api/execute/stream", {
875
+ method: "POST",
876
+ headers: {
877
+ "Content-Type": "application/json"
878
+ },
879
+ body: JSON.stringify(data)
880
+ });
881
+ const stream = await this.handleStreamResponse(response);
882
+ this.logSuccess("Command stream started", command);
883
+ return stream;
884
+ } catch (error) {
885
+ this.logError("executeStream", error);
886
+ this.options.onError?.(
887
+ error instanceof Error ? error.message : String(error),
888
+ command
889
+ );
890
+ throw error;
891
+ }
892
+ }
893
+ };
894
+
895
+ // src/clients/file-client.ts
896
+ var FileClient = class extends BaseHttpClient {
897
+ /**
898
+ * Create a directory
899
+ * @param path - Directory path to create
900
+ * @param sessionId - The session ID for this operation
901
+ * @param options - Optional settings (recursive)
902
+ */
903
+ async mkdir(path, sessionId, options) {
904
+ try {
905
+ const data = {
906
+ path,
907
+ sessionId,
908
+ recursive: options?.recursive ?? false
909
+ };
910
+ const response = await this.post("/api/mkdir", data);
911
+ this.logSuccess("Directory created", `${path} (recursive: ${data.recursive})`);
912
+ return response;
913
+ } catch (error) {
914
+ this.logError("mkdir", error);
915
+ throw error;
916
+ }
917
+ }
918
+ /**
919
+ * Write content to a file
920
+ * @param path - File path to write to
921
+ * @param content - Content to write
922
+ * @param sessionId - The session ID for this operation
923
+ * @param options - Optional settings (encoding)
924
+ */
925
+ async writeFile(path, content, sessionId, options) {
926
+ try {
927
+ const data = {
928
+ path,
929
+ content,
930
+ sessionId,
931
+ encoding: options?.encoding ?? "utf8"
932
+ };
933
+ const response = await this.post("/api/write", data);
934
+ this.logSuccess("File written", `${path} (${content.length} chars)`);
935
+ return response;
936
+ } catch (error) {
937
+ this.logError("writeFile", error);
938
+ throw error;
939
+ }
940
+ }
941
+ /**
942
+ * Read content from a file
943
+ * @param path - File path to read from
944
+ * @param sessionId - The session ID for this operation
945
+ * @param options - Optional settings (encoding)
946
+ */
947
+ async readFile(path, sessionId, options) {
948
+ try {
949
+ const data = {
950
+ path,
951
+ sessionId,
952
+ encoding: options?.encoding ?? "utf8"
953
+ };
954
+ const response = await this.post("/api/read", data);
955
+ this.logSuccess("File read", `${path} (${response.content.length} chars)`);
956
+ return response;
957
+ } catch (error) {
958
+ this.logError("readFile", error);
959
+ throw error;
960
+ }
961
+ }
962
+ /**
963
+ * Stream a file using Server-Sent Events
964
+ * Returns a ReadableStream of SSE events containing metadata, chunks, and completion
965
+ * @param path - File path to stream
966
+ * @param sessionId - The session ID for this operation
967
+ */
968
+ async readFileStream(path, sessionId) {
969
+ try {
970
+ const data = {
971
+ path,
972
+ sessionId
973
+ };
974
+ const response = await this.doFetch("/api/read/stream", {
975
+ method: "POST",
976
+ headers: {
977
+ "Content-Type": "application/json"
978
+ },
979
+ body: JSON.stringify(data)
980
+ });
981
+ const stream = await this.handleStreamResponse(response);
982
+ this.logSuccess("File stream started", path);
983
+ return stream;
984
+ } catch (error) {
985
+ this.logError("readFileStream", error);
986
+ throw error;
987
+ }
988
+ }
989
+ /**
990
+ * Delete a file
991
+ * @param path - File path to delete
992
+ * @param sessionId - The session ID for this operation
993
+ */
994
+ async deleteFile(path, sessionId) {
995
+ try {
996
+ const data = { path, sessionId };
997
+ const response = await this.post("/api/delete", data);
998
+ this.logSuccess("File deleted", path);
999
+ return response;
1000
+ } catch (error) {
1001
+ this.logError("deleteFile", error);
1002
+ throw error;
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Rename a file
1007
+ * @param path - Current file path
1008
+ * @param newPath - New file path
1009
+ * @param sessionId - The session ID for this operation
1010
+ */
1011
+ async renameFile(path, newPath, sessionId) {
1012
+ try {
1013
+ const data = { oldPath: path, newPath, sessionId };
1014
+ const response = await this.post("/api/rename", data);
1015
+ this.logSuccess("File renamed", `${path} -> ${newPath}`);
1016
+ return response;
1017
+ } catch (error) {
1018
+ this.logError("renameFile", error);
1019
+ throw error;
1020
+ }
1021
+ }
1022
+ /**
1023
+ * Move a file
1024
+ * @param path - Current file path
1025
+ * @param newPath - Destination file path
1026
+ * @param sessionId - The session ID for this operation
1027
+ */
1028
+ async moveFile(path, newPath, sessionId) {
1029
+ try {
1030
+ const data = { sourcePath: path, destinationPath: newPath, sessionId };
1031
+ const response = await this.post("/api/move", data);
1032
+ this.logSuccess("File moved", `${path} -> ${newPath}`);
1033
+ return response;
1034
+ } catch (error) {
1035
+ this.logError("moveFile", error);
1036
+ throw error;
1037
+ }
1038
+ }
1039
+ /**
1040
+ * List files in a directory
1041
+ * @param path - Directory path to list
1042
+ * @param sessionId - The session ID for this operation
1043
+ * @param options - Optional settings (recursive, includeHidden)
1044
+ */
1045
+ async listFiles(path, sessionId, options) {
1046
+ try {
1047
+ const data = {
1048
+ path,
1049
+ sessionId,
1050
+ options: options || {}
1051
+ };
1052
+ const response = await this.post("/api/list-files", data);
1053
+ this.logSuccess("Files listed", `${path} (${response.count} files)`);
1054
+ return response;
1055
+ } catch (error) {
1056
+ this.logError("listFiles", error);
1057
+ throw error;
1058
+ }
1059
+ }
1060
+ };
1061
+
1062
+ // src/clients/git-client.ts
1063
+ var GitClient = class extends BaseHttpClient {
1064
+ /**
1065
+ * Clone a Git repository
1066
+ * @param repoUrl - URL of the Git repository to clone
1067
+ * @param sessionId - The session ID for this operation
1068
+ * @param options - Optional settings (branch, targetDir)
1069
+ */
1070
+ async checkout(repoUrl, sessionId, options) {
1071
+ try {
1072
+ let targetDir = options?.targetDir;
1073
+ if (!targetDir) {
1074
+ const repoName = this.extractRepoName(repoUrl);
1075
+ targetDir = `/workspace/${repoName}`;
1076
+ }
1077
+ const data = {
1078
+ repoUrl,
1079
+ sessionId,
1080
+ targetDir
1081
+ };
1082
+ if (options?.branch) {
1083
+ data.branch = options.branch;
1084
+ }
1085
+ const response = await this.post(
1086
+ "/api/git/checkout",
1087
+ data
1088
+ );
1089
+ this.logSuccess(
1090
+ "Repository cloned",
1091
+ `${repoUrl} (branch: ${response.branch}) -> ${response.targetDir}`
1092
+ );
1093
+ return response;
1094
+ } catch (error) {
1095
+ this.logError("checkout", error);
1096
+ throw error;
1097
+ }
1098
+ }
1099
+ /**
1100
+ * Extract repository name from URL for default directory name
1101
+ */
1102
+ extractRepoName(repoUrl) {
1103
+ try {
1104
+ const url = new URL(repoUrl);
1105
+ const pathParts = url.pathname.split("/");
1106
+ const repoName = pathParts[pathParts.length - 1];
1107
+ return repoName.replace(/\.git$/, "");
1108
+ } catch {
1109
+ const parts = repoUrl.split("/");
1110
+ const repoName = parts[parts.length - 1];
1111
+ return repoName.replace(/\.git$/, "") || "repo";
1112
+ }
1113
+ }
1114
+ };
1115
+
1116
+ // src/clients/interpreter-client.ts
1117
+ var InterpreterClient = class extends BaseHttpClient {
1118
+ maxRetries = 3;
1119
+ retryDelayMs = 1e3;
1120
+ async createCodeContext(options = {}) {
1121
+ return this.executeWithRetry(async () => {
1122
+ const response = await this.doFetch("/api/contexts", {
1123
+ method: "POST",
1124
+ headers: { "Content-Type": "application/json" },
1125
+ body: JSON.stringify({
1126
+ language: options.language || "python",
1127
+ cwd: options.cwd || "/workspace",
1128
+ env_vars: options.envVars
1129
+ })
1130
+ });
1131
+ if (!response.ok) {
1132
+ const error = await this.parseErrorResponse(response);
1133
+ throw error;
1134
+ }
1135
+ const data = await response.json();
1136
+ if (!data.success) {
1137
+ throw new Error(`Failed to create context: ${JSON.stringify(data)}`);
1138
+ }
1139
+ return {
1140
+ id: data.contextId,
1141
+ language: data.language,
1142
+ cwd: data.cwd || "/workspace",
1143
+ createdAt: new Date(data.timestamp),
1144
+ lastUsed: new Date(data.timestamp)
1145
+ };
1146
+ });
1147
+ }
1148
+ async runCodeStream(contextId, code, language, callbacks, timeoutMs) {
1149
+ return this.executeWithRetry(async () => {
1150
+ const response = await this.doFetch("/api/execute/code", {
1151
+ method: "POST",
1152
+ headers: {
1153
+ "Content-Type": "application/json",
1154
+ Accept: "text/event-stream"
1155
+ },
1156
+ body: JSON.stringify({
1157
+ context_id: contextId,
1158
+ code,
1159
+ language,
1160
+ ...timeoutMs !== void 0 && { timeout_ms: timeoutMs }
1161
+ })
1162
+ });
1163
+ if (!response.ok) {
1164
+ const error = await this.parseErrorResponse(response);
1165
+ throw error;
1166
+ }
1167
+ if (!response.body) {
1168
+ throw new Error("No response body for streaming execution");
1169
+ }
1170
+ for await (const chunk of this.readLines(response.body)) {
1171
+ await this.parseExecutionResult(chunk, callbacks);
1172
+ }
1173
+ });
1174
+ }
1175
+ async listCodeContexts() {
1176
+ return this.executeWithRetry(async () => {
1177
+ const response = await this.doFetch("/api/contexts", {
1178
+ method: "GET",
1179
+ headers: { "Content-Type": "application/json" }
1180
+ });
1181
+ if (!response.ok) {
1182
+ const error = await this.parseErrorResponse(response);
1183
+ throw error;
1184
+ }
1185
+ const data = await response.json();
1186
+ if (!data.success) {
1187
+ throw new Error(`Failed to list contexts: ${JSON.stringify(data)}`);
1188
+ }
1189
+ return data.contexts.map((ctx) => ({
1190
+ id: ctx.id,
1191
+ language: ctx.language,
1192
+ cwd: ctx.cwd || "/workspace",
1193
+ createdAt: new Date(data.timestamp),
1194
+ lastUsed: new Date(data.timestamp)
1195
+ }));
1196
+ });
1197
+ }
1198
+ async deleteCodeContext(contextId) {
1199
+ return this.executeWithRetry(async () => {
1200
+ const response = await this.doFetch(`/api/contexts/${contextId}`, {
1201
+ method: "DELETE",
1202
+ headers: { "Content-Type": "application/json" }
1203
+ });
1204
+ if (!response.ok) {
1205
+ const error = await this.parseErrorResponse(response);
1206
+ throw error;
1207
+ }
1208
+ });
1209
+ }
1210
+ /**
1211
+ * Execute an operation with automatic retry for transient errors
1212
+ */
1213
+ async executeWithRetry(operation) {
1214
+ let lastError;
1215
+ for (let attempt = 0; attempt < this.maxRetries; attempt++) {
1216
+ try {
1217
+ return await operation();
1218
+ } catch (error) {
1219
+ this.logError("executeWithRetry", error);
1220
+ lastError = error;
1221
+ if (this.isRetryableError(error)) {
1222
+ if (attempt < this.maxRetries - 1) {
1223
+ const delay = this.retryDelayMs * 2 ** attempt + Math.random() * 1e3;
1224
+ await new Promise((resolve) => setTimeout(resolve, delay));
1225
+ continue;
1226
+ }
1227
+ }
1228
+ throw error;
1229
+ }
1230
+ }
1231
+ throw lastError || new Error("Execution failed after retries");
1232
+ }
1233
+ isRetryableError(error) {
1234
+ if (error instanceof InterpreterNotReadyError) {
1235
+ return true;
1236
+ }
1237
+ if (error instanceof Error) {
1238
+ return error.message.includes("not ready") || error.message.includes("initializing");
1239
+ }
1240
+ return false;
1241
+ }
1242
+ async parseErrorResponse(response) {
1243
+ try {
1244
+ const errorData = await response.json();
1245
+ return createErrorFromResponse(errorData);
1246
+ } catch {
1247
+ const errorResponse = {
1248
+ code: ErrorCode.INTERNAL_ERROR,
1249
+ message: `HTTP ${response.status}: ${response.statusText}`,
1250
+ context: {},
1251
+ httpStatus: response.status,
1252
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1253
+ };
1254
+ return createErrorFromResponse(errorResponse);
1255
+ }
1256
+ }
1257
+ async *readLines(stream) {
1258
+ const reader = stream.getReader();
1259
+ let buffer = "";
1260
+ try {
1261
+ while (true) {
1262
+ const { done, value } = await reader.read();
1263
+ if (value) {
1264
+ buffer += new TextDecoder().decode(value);
1265
+ }
1266
+ if (done) break;
1267
+ let newlineIdx = buffer.indexOf("\n");
1268
+ while (newlineIdx !== -1) {
1269
+ yield buffer.slice(0, newlineIdx);
1270
+ buffer = buffer.slice(newlineIdx + 1);
1271
+ newlineIdx = buffer.indexOf("\n");
1272
+ }
1273
+ }
1274
+ if (buffer.length > 0) {
1275
+ yield buffer;
1276
+ }
1277
+ } finally {
1278
+ reader.releaseLock();
1279
+ }
1280
+ }
1281
+ async parseExecutionResult(line, callbacks) {
1282
+ if (!line.trim()) return;
1283
+ if (!line.startsWith("data: ")) return;
1284
+ try {
1285
+ const jsonData = line.substring(6);
1286
+ const data = JSON.parse(jsonData);
1287
+ switch (data.type) {
1288
+ case "stdout":
1289
+ if (callbacks.onStdout && data.text) {
1290
+ await callbacks.onStdout({
1291
+ text: data.text,
1292
+ timestamp: data.timestamp || Date.now()
1293
+ });
1294
+ }
1295
+ break;
1296
+ case "stderr":
1297
+ if (callbacks.onStderr && data.text) {
1298
+ await callbacks.onStderr({
1299
+ text: data.text,
1300
+ timestamp: data.timestamp || Date.now()
1301
+ });
1302
+ }
1303
+ break;
1304
+ case "result":
1305
+ if (callbacks.onResult) {
1306
+ const result = new ResultImpl(data);
1307
+ await callbacks.onResult(result);
1308
+ }
1309
+ break;
1310
+ case "error":
1311
+ if (callbacks.onError) {
1312
+ await callbacks.onError({
1313
+ name: data.ename || "Error",
1314
+ message: data.evalue || "Unknown error",
1315
+ traceback: data.traceback || []
1316
+ });
1317
+ }
1318
+ break;
1319
+ case "execution_complete":
1320
+ break;
1321
+ }
1322
+ } catch (error) {
1323
+ this.logError("parseExecutionResult", error);
1324
+ }
1325
+ }
1326
+ };
1327
+
1328
+ // src/clients/port-client.ts
1329
+ var PortClient = class extends BaseHttpClient {
1330
+ /**
1331
+ * Expose a port and get a preview URL
1332
+ * @param port - Port number to expose
1333
+ * @param sessionId - The session ID for this operation
1334
+ * @param name - Optional name for the port
1335
+ */
1336
+ async exposePort(port, sessionId, name) {
1337
+ try {
1338
+ const data = { port, sessionId, name };
1339
+ const response = await this.post(
1340
+ "/api/expose-port",
1341
+ data
1342
+ );
1343
+ this.logSuccess(
1344
+ "Port exposed",
1345
+ `${port} exposed at ${response.url}${name ? ` (${name})` : ""}`
1346
+ );
1347
+ return response;
1348
+ } catch (error) {
1349
+ this.logError("exposePort", error);
1350
+ throw error;
1351
+ }
1352
+ }
1353
+ /**
1354
+ * Unexpose a port and remove its preview URL
1355
+ * @param port - Port number to unexpose
1356
+ * @param sessionId - The session ID for this operation
1357
+ */
1358
+ async unexposePort(port, sessionId) {
1359
+ try {
1360
+ const url = `/api/exposed-ports/${port}?session=${encodeURIComponent(sessionId)}`;
1361
+ const response = await this.delete(url);
1362
+ this.logSuccess("Port unexposed", `${port}`);
1363
+ return response;
1364
+ } catch (error) {
1365
+ this.logError("unexposePort", error);
1366
+ throw error;
1367
+ }
1368
+ }
1369
+ /**
1370
+ * Get all currently exposed ports
1371
+ * @param sessionId - The session ID for this operation
1372
+ */
1373
+ async getExposedPorts(sessionId) {
1374
+ try {
1375
+ const url = `/api/exposed-ports?session=${encodeURIComponent(sessionId)}`;
1376
+ const response = await this.get(url);
1377
+ this.logSuccess(
1378
+ "Exposed ports retrieved",
1379
+ `${response.ports.length} ports exposed`
1380
+ );
1381
+ return response;
1382
+ } catch (error) {
1383
+ this.logError("getExposedPorts", error);
1384
+ throw error;
1385
+ }
1386
+ }
1387
+ };
1388
+
1389
+ // src/clients/process-client.ts
1390
+ var ProcessClient = class extends BaseHttpClient {
1391
+ /**
1392
+ * Start a background process
1393
+ * @param command - Command to execute as a background process
1394
+ * @param sessionId - The session ID for this operation
1395
+ * @param options - Optional settings (processId)
1396
+ */
1397
+ async startProcess(command, sessionId, options) {
1398
+ try {
1399
+ const data = {
1400
+ command,
1401
+ sessionId,
1402
+ processId: options?.processId
1403
+ };
1404
+ const response = await this.post(
1405
+ "/api/process/start",
1406
+ data
1407
+ );
1408
+ this.logSuccess(
1409
+ "Process started",
1410
+ `${command} (ID: ${response.processId})`
1411
+ );
1412
+ return response;
1413
+ } catch (error) {
1414
+ this.logError("startProcess", error);
1415
+ throw error;
1416
+ }
1417
+ }
1418
+ /**
1419
+ * List all processes (sandbox-scoped, not session-scoped)
1420
+ */
1421
+ async listProcesses() {
1422
+ try {
1423
+ const url = `/api/process/list`;
1424
+ const response = await this.get(url);
1425
+ this.logSuccess("Processes listed", `${response.processes.length} processes`);
1426
+ return response;
1427
+ } catch (error) {
1428
+ this.logError("listProcesses", error);
1429
+ throw error;
1430
+ }
1431
+ }
1432
+ /**
1433
+ * Get information about a specific process (sandbox-scoped, not session-scoped)
1434
+ * @param processId - ID of the process to retrieve
1435
+ */
1436
+ async getProcess(processId) {
1437
+ try {
1438
+ const url = `/api/process/${processId}`;
1439
+ const response = await this.get(url);
1440
+ this.logSuccess("Process retrieved", `ID: ${processId}`);
1441
+ return response;
1442
+ } catch (error) {
1443
+ this.logError("getProcess", error);
1444
+ throw error;
1445
+ }
1446
+ }
1447
+ /**
1448
+ * Kill a specific process (sandbox-scoped, not session-scoped)
1449
+ * @param processId - ID of the process to kill
1450
+ */
1451
+ async killProcess(processId) {
1452
+ try {
1453
+ const url = `/api/process/${processId}`;
1454
+ const response = await this.delete(url);
1455
+ this.logSuccess("Process killed", `ID: ${processId}`);
1456
+ return response;
1457
+ } catch (error) {
1458
+ this.logError("killProcess", error);
1459
+ throw error;
1460
+ }
1461
+ }
1462
+ /**
1463
+ * Kill all running processes (sandbox-scoped, not session-scoped)
1464
+ */
1465
+ async killAllProcesses() {
1466
+ try {
1467
+ const url = `/api/process/kill-all`;
1468
+ const response = await this.delete(url);
1469
+ this.logSuccess(
1470
+ "All processes killed",
1471
+ `${response.cleanedCount} processes terminated`
1472
+ );
1473
+ return response;
1474
+ } catch (error) {
1475
+ this.logError("killAllProcesses", error);
1476
+ throw error;
1477
+ }
1478
+ }
1479
+ /**
1480
+ * Get logs from a specific process (sandbox-scoped, not session-scoped)
1481
+ * @param processId - ID of the process to get logs from
1482
+ */
1483
+ async getProcessLogs(processId) {
1484
+ try {
1485
+ const url = `/api/process/${processId}/logs`;
1486
+ const response = await this.get(url);
1487
+ this.logSuccess(
1488
+ "Process logs retrieved",
1489
+ `ID: ${processId}, stdout: ${response.stdout.length} chars, stderr: ${response.stderr.length} chars`
1490
+ );
1491
+ return response;
1492
+ } catch (error) {
1493
+ this.logError("getProcessLogs", error);
1494
+ throw error;
1495
+ }
1496
+ }
1497
+ /**
1498
+ * Stream logs from a specific process (sandbox-scoped, not session-scoped)
1499
+ * @param processId - ID of the process to stream logs from
1500
+ */
1501
+ async streamProcessLogs(processId) {
1502
+ try {
1503
+ const url = `/api/process/${processId}/stream`;
1504
+ const response = await this.doFetch(url, {
1505
+ method: "GET"
1506
+ });
1507
+ const stream = await this.handleStreamResponse(response);
1508
+ this.logSuccess("Process log stream started", `ID: ${processId}`);
1509
+ return stream;
1510
+ } catch (error) {
1511
+ this.logError("streamProcessLogs", error);
1512
+ throw error;
1513
+ }
1514
+ }
1515
+ };
1516
+
1517
+ // src/clients/utility-client.ts
1518
+ var UtilityClient = class extends BaseHttpClient {
1519
+ /**
1520
+ * Ping the sandbox to check if it's responsive
1521
+ */
1522
+ async ping() {
1523
+ try {
1524
+ const response = await this.get("/api/ping");
1525
+ this.logSuccess("Ping successful", response.message);
1526
+ return response.message;
1527
+ } catch (error) {
1528
+ this.logError("ping", error);
1529
+ throw error;
1530
+ }
1531
+ }
1532
+ /**
1533
+ * Get list of available commands in the sandbox environment
1534
+ */
1535
+ async getCommands() {
1536
+ try {
1537
+ const response = await this.get("/api/commands");
1538
+ this.logSuccess(
1539
+ "Commands retrieved",
1540
+ `${response.count} commands available`
1541
+ );
1542
+ return response.availableCommands;
1543
+ } catch (error) {
1544
+ this.logError("getCommands", error);
1545
+ throw error;
1546
+ }
1547
+ }
1548
+ /**
1549
+ * Create a new execution session
1550
+ * @param options - Session configuration (id, env, cwd)
1551
+ */
1552
+ async createSession(options) {
1553
+ try {
1554
+ const response = await this.post(
1555
+ "/api/session/create",
1556
+ options
1557
+ );
1558
+ this.logSuccess("Session created", `ID: ${options.id}`);
1559
+ return response;
1560
+ } catch (error) {
1561
+ this.logError("createSession", error);
1562
+ throw error;
1563
+ }
1564
+ }
1565
+ };
1566
+
1567
+ // src/clients/sandbox-client.ts
1568
+ var SandboxClient = class {
1569
+ commands;
1570
+ files;
1571
+ processes;
1572
+ ports;
1573
+ git;
1574
+ interpreter;
1575
+ utils;
1576
+ constructor(options) {
1577
+ const clientOptions = {
1578
+ baseUrl: "http://localhost:3000",
1579
+ ...options
1580
+ };
1581
+ this.commands = new CommandClient(clientOptions);
1582
+ this.files = new FileClient(clientOptions);
1583
+ this.processes = new ProcessClient(clientOptions);
1584
+ this.ports = new PortClient(clientOptions);
1585
+ this.git = new GitClient(clientOptions);
1586
+ this.interpreter = new InterpreterClient(clientOptions);
1587
+ this.utils = new UtilityClient(clientOptions);
1588
+ }
1589
+ };
1590
+
1591
+ // src/sandbox.ts
1592
+ function getSandbox(ns, id, options) {
1593
+ const stub = getContainer(ns, id);
1594
+ stub.setSandboxName?.(id);
1595
+ if (options?.baseUrl) {
1596
+ stub.setBaseUrl(options.baseUrl);
1597
+ }
1598
+ return stub;
1599
+ }
1600
+ var Sandbox = class extends Container {
1601
+ defaultPort = 3e3;
1602
+ // Default port for the container's Bun server
1603
+ sleepAfter = "3m";
1604
+ // Sleep the sandbox if no requests are made in this timeframe
1605
+ client;
1606
+ codeInterpreter;
1607
+ sandboxName = null;
1608
+ baseUrl = null;
1609
+ portTokens = /* @__PURE__ */ new Map();
1610
+ defaultSession = null;
1611
+ envVars = {};
1612
+ logger;
1613
+ constructor(ctx, env) {
1614
+ super(ctx, env);
1615
+ const envObj = env;
1616
+ const sandboxEnvKeys = ["SANDBOX_LOG_LEVEL", "SANDBOX_LOG_FORMAT"];
1617
+ sandboxEnvKeys.forEach((key) => {
1618
+ if (envObj?.[key]) {
1619
+ this.envVars[key] = envObj[key];
1620
+ }
1621
+ });
1622
+ this.logger = createLogger({
1623
+ component: "sandbox-do",
1624
+ sandboxId: this.ctx.id.toString()
1625
+ });
1626
+ this.client = new SandboxClient({
1627
+ logger: this.logger,
1628
+ port: 3e3,
1629
+ // Control plane port
1630
+ stub: this
1631
+ });
1632
+ this.codeInterpreter = new CodeInterpreter(this);
1633
+ this.ctx.blockConcurrencyWhile(async () => {
1634
+ this.sandboxName = await this.ctx.storage.get("sandboxName") || null;
1635
+ const storedTokens = await this.ctx.storage.get("portTokens") || {};
1636
+ this.portTokens = /* @__PURE__ */ new Map();
1637
+ for (const [portStr, token] of Object.entries(storedTokens)) {
1638
+ this.portTokens.set(parseInt(portStr, 10), token);
1639
+ }
1640
+ });
1641
+ }
1642
+ // RPC method to set the sandbox name
1643
+ async setSandboxName(name) {
1644
+ if (!this.sandboxName) {
1645
+ this.sandboxName = name;
1646
+ await this.ctx.storage.put("sandboxName", name);
1647
+ }
1648
+ }
1649
+ // RPC method to set the base URL
1650
+ async setBaseUrl(baseUrl) {
1651
+ if (!this.baseUrl) {
1652
+ this.baseUrl = baseUrl;
1653
+ await this.ctx.storage.put("baseUrl", baseUrl);
1654
+ console.log(`[Sandbox] Stored base URL: ${baseUrl}`);
1655
+ } else {
1656
+ if (this.baseUrl !== baseUrl) {
1657
+ throw new Error("Base URL already set and different from one previously provided");
1658
+ }
1659
+ }
1660
+ }
1661
+ // RPC method to set environment variables
1662
+ async setEnvVars(envVars) {
1663
+ this.envVars = { ...this.envVars, ...envVars };
1664
+ if (this.defaultSession) {
1665
+ for (const [key, value] of Object.entries(envVars)) {
1666
+ const escapedValue = value.replace(/'/g, "'\\''");
1667
+ const exportCommand = `export ${key}='${escapedValue}'`;
1668
+ const result = await this.client.commands.execute(exportCommand, this.defaultSession);
1669
+ if (result.exitCode !== 0) {
1670
+ throw new Error(`Failed to set ${key}: ${result.stderr || "Unknown error"}`);
1671
+ }
1672
+ }
1673
+ }
1674
+ }
1675
+ /**
1676
+ * Cleanup and destroy the sandbox container
1677
+ */
1678
+ async destroy() {
1679
+ this.logger.info("Destroying sandbox container");
1680
+ await super.destroy();
1681
+ }
1682
+ onStart() {
1683
+ this.logger.debug("Sandbox started");
1684
+ }
1685
+ onStop() {
1686
+ this.logger.debug("Sandbox stopped");
1687
+ }
1688
+ onError(error) {
1689
+ this.logger.error("Sandbox error", error instanceof Error ? error : new Error(String(error)));
1690
+ }
1691
+ // Override fetch to route internal container requests to appropriate ports
1692
+ async fetch(request) {
1693
+ const traceId = TraceContext.fromHeaders(request.headers) || TraceContext.generate();
1694
+ const requestLogger = this.logger.child({ traceId, operation: "fetch" });
1695
+ return await runWithLogger(requestLogger, async () => {
1696
+ const url = new URL(request.url);
1697
+ if (!this.sandboxName && request.headers.has("X-Sandbox-Name")) {
1698
+ const name = request.headers.get("X-Sandbox-Name");
1699
+ this.sandboxName = name;
1700
+ await this.ctx.storage.put("sandboxName", name);
1701
+ }
1702
+ const port = this.determinePort(url);
1703
+ return await this.containerFetch(request, port);
1704
+ });
1705
+ }
1706
+ determinePort(url) {
1707
+ const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
1708
+ if (proxyMatch) {
1709
+ return parseInt(proxyMatch[1], 10);
1710
+ }
1711
+ return 3e3;
1712
+ }
1713
+ /**
1714
+ * Ensure default session exists - lazy initialization
1715
+ * This is called automatically by all public methods that need a session
1716
+ */
1717
+ async ensureDefaultSession() {
1718
+ if (!this.defaultSession) {
1719
+ const sessionId = `sandbox-${this.sandboxName || "default"}`;
1720
+ await this.client.utils.createSession({
1721
+ id: sessionId,
1722
+ env: this.envVars || {},
1723
+ cwd: "/workspace"
1724
+ });
1725
+ this.defaultSession = sessionId;
1726
+ this.logger.debug("Default session initialized", { sessionId });
1727
+ }
1728
+ return this.defaultSession;
1729
+ }
1730
+ // Enhanced exec method - always returns ExecResult with optional streaming
1731
+ // This replaces the old exec method to match ISandbox interface
1732
+ async exec(command, options) {
1733
+ const session = await this.ensureDefaultSession();
1734
+ return this.execWithSession(command, session, options);
1735
+ }
1736
+ /**
1737
+ * Internal session-aware exec implementation
1738
+ * Used by both public exec() and session wrappers
1739
+ */
1740
+ async execWithSession(command, sessionId, options) {
1741
+ const startTime = Date.now();
1742
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1743
+ let timeoutId;
1744
+ try {
1745
+ if (options?.signal?.aborted) {
1746
+ throw new Error("Operation was aborted");
1747
+ }
1748
+ let result;
1749
+ if (options?.stream && options?.onOutput) {
1750
+ result = await this.executeWithStreaming(command, sessionId, options, startTime, timestamp);
1751
+ } else {
1752
+ const response = await this.client.commands.execute(command, sessionId);
1753
+ const duration = Date.now() - startTime;
1754
+ result = this.mapExecuteResponseToExecResult(response, duration, sessionId);
1755
+ }
1756
+ if (options?.onComplete) {
1757
+ options.onComplete(result);
1758
+ }
1759
+ return result;
1760
+ } catch (error) {
1761
+ if (options?.onError && error instanceof Error) {
1762
+ options.onError(error);
1763
+ }
1764
+ throw error;
1765
+ } finally {
1766
+ if (timeoutId) {
1767
+ clearTimeout(timeoutId);
1768
+ }
1769
+ }
1770
+ }
1771
+ async executeWithStreaming(command, sessionId, options, startTime, timestamp) {
1772
+ let stdout = "";
1773
+ let stderr = "";
1774
+ try {
1775
+ const stream = await this.client.commands.executeStream(command, sessionId);
1776
+ for await (const event of parseSSEStream(stream)) {
1777
+ if (options.signal?.aborted) {
1778
+ throw new Error("Operation was aborted");
1779
+ }
1780
+ switch (event.type) {
1781
+ case "stdout":
1782
+ case "stderr":
1783
+ if (event.data) {
1784
+ if (event.type === "stdout") stdout += event.data;
1785
+ if (event.type === "stderr") stderr += event.data;
1786
+ if (options.onOutput) {
1787
+ options.onOutput(event.type, event.data);
1788
+ }
1789
+ }
1790
+ break;
1791
+ case "complete": {
1792
+ const duration = Date.now() - startTime;
1793
+ return {
1794
+ success: (event.exitCode ?? 0) === 0,
1795
+ exitCode: event.exitCode ?? 0,
1796
+ stdout,
1797
+ stderr,
1798
+ command,
1799
+ duration,
1800
+ timestamp,
1801
+ sessionId
1802
+ };
1803
+ }
1804
+ case "error":
1805
+ throw new Error(event.data || "Command execution failed");
1806
+ }
1807
+ }
1808
+ throw new Error("Stream ended without completion event");
1809
+ } catch (error) {
1810
+ if (options.signal?.aborted) {
1811
+ throw new Error("Operation was aborted");
1812
+ }
1813
+ throw error;
1814
+ }
1815
+ }
1816
+ mapExecuteResponseToExecResult(response, duration, sessionId) {
1817
+ return {
1818
+ success: response.success,
1819
+ exitCode: response.exitCode,
1820
+ stdout: response.stdout,
1821
+ stderr: response.stderr,
1822
+ command: response.command,
1823
+ duration,
1824
+ timestamp: response.timestamp,
1825
+ sessionId
1826
+ };
1827
+ }
1828
+ /**
1829
+ * Create a Process domain object from HTTP client DTO
1830
+ * Centralizes process object creation with bound methods
1831
+ * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers
1832
+ */
1833
+ createProcessFromDTO(data, sessionId) {
1834
+ return {
1835
+ id: data.id,
1836
+ pid: data.pid,
1837
+ command: data.command,
1838
+ status: data.status,
1839
+ startTime: typeof data.startTime === "string" ? new Date(data.startTime) : data.startTime,
1840
+ endTime: data.endTime ? typeof data.endTime === "string" ? new Date(data.endTime) : data.endTime : void 0,
1841
+ exitCode: data.exitCode,
1842
+ sessionId,
1843
+ kill: async (signal) => {
1844
+ await this.killProcess(data.id, signal);
1845
+ },
1846
+ getStatus: async () => {
1847
+ const current = await this.getProcess(data.id);
1848
+ return current?.status || "error";
1849
+ },
1850
+ getLogs: async () => {
1851
+ const logs = await this.getProcessLogs(data.id);
1852
+ return { stdout: logs.stdout, stderr: logs.stderr };
1853
+ }
1854
+ };
1855
+ }
1856
+ // Background process management
1857
+ async startProcess(command, options, sessionId) {
1858
+ try {
1859
+ const session = sessionId ?? await this.ensureDefaultSession();
1860
+ const response = await this.client.processes.startProcess(command, session, {
1861
+ processId: options?.processId
1862
+ });
1863
+ const processObj = this.createProcessFromDTO({
1864
+ id: response.processId,
1865
+ pid: response.pid,
1866
+ command: response.command,
1867
+ status: "running",
1868
+ startTime: /* @__PURE__ */ new Date(),
1869
+ endTime: void 0,
1870
+ exitCode: void 0
1871
+ }, session);
1872
+ if (options?.onStart) {
1873
+ options.onStart(processObj);
1874
+ }
1875
+ return processObj;
1876
+ } catch (error) {
1877
+ if (options?.onError && error instanceof Error) {
1878
+ options.onError(error);
1879
+ }
1880
+ throw error;
1881
+ }
1882
+ }
1883
+ async listProcesses(sessionId) {
1884
+ const session = sessionId ?? await this.ensureDefaultSession();
1885
+ const response = await this.client.processes.listProcesses();
1886
+ return response.processes.map(
1887
+ (processData) => this.createProcessFromDTO({
1888
+ id: processData.id,
1889
+ pid: processData.pid,
1890
+ command: processData.command,
1891
+ status: processData.status,
1892
+ startTime: processData.startTime,
1893
+ endTime: processData.endTime,
1894
+ exitCode: processData.exitCode
1895
+ }, session)
1896
+ );
1897
+ }
1898
+ async getProcess(id, sessionId) {
1899
+ const session = sessionId ?? await this.ensureDefaultSession();
1900
+ const response = await this.client.processes.getProcess(id);
1901
+ if (!response.process) {
1902
+ return null;
1903
+ }
1904
+ const processData = response.process;
1905
+ return this.createProcessFromDTO({
1906
+ id: processData.id,
1907
+ pid: processData.pid,
1908
+ command: processData.command,
1909
+ status: processData.status,
1910
+ startTime: processData.startTime,
1911
+ endTime: processData.endTime,
1912
+ exitCode: processData.exitCode
1913
+ }, session);
1914
+ }
1915
+ async killProcess(id, signal, sessionId) {
1916
+ await this.client.processes.killProcess(id);
1917
+ }
1918
+ async killAllProcesses(sessionId) {
1919
+ const response = await this.client.processes.killAllProcesses();
1920
+ return response.cleanedCount;
1921
+ }
1922
+ async cleanupCompletedProcesses(sessionId) {
1923
+ return 0;
1924
+ }
1925
+ async getProcessLogs(id, sessionId) {
1926
+ const response = await this.client.processes.getProcessLogs(id);
1927
+ return {
1928
+ stdout: response.stdout,
1929
+ stderr: response.stderr,
1930
+ processId: response.processId
1931
+ };
1932
+ }
1933
+ // Streaming methods - return ReadableStream for RPC compatibility
1934
+ async execStream(command, options) {
1935
+ if (options?.signal?.aborted) {
1936
+ throw new Error("Operation was aborted");
1937
+ }
1938
+ const session = await this.ensureDefaultSession();
1939
+ return this.client.commands.executeStream(command, session);
1940
+ }
1941
+ /**
1942
+ * Internal session-aware execStream implementation
1943
+ */
1944
+ async execStreamWithSession(command, sessionId, options) {
1945
+ if (options?.signal?.aborted) {
1946
+ throw new Error("Operation was aborted");
1947
+ }
1948
+ return this.client.commands.executeStream(command, sessionId);
1949
+ }
1950
+ async streamProcessLogs(processId, options) {
1951
+ if (options?.signal?.aborted) {
1952
+ throw new Error("Operation was aborted");
1953
+ }
1954
+ return this.client.processes.streamProcessLogs(processId);
1955
+ }
1956
+ async gitCheckout(repoUrl, options) {
1957
+ const session = options.sessionId ?? await this.ensureDefaultSession();
1958
+ return this.client.git.checkout(repoUrl, session, {
1959
+ branch: options.branch,
1960
+ targetDir: options.targetDir
1961
+ });
1962
+ }
1963
+ async mkdir(path, options = {}) {
1964
+ const session = options.sessionId ?? await this.ensureDefaultSession();
1965
+ return this.client.files.mkdir(path, session, { recursive: options.recursive });
1966
+ }
1967
+ async writeFile(path, content, options = {}) {
1968
+ const session = options.sessionId ?? await this.ensureDefaultSession();
1969
+ return this.client.files.writeFile(path, content, session, { encoding: options.encoding });
1970
+ }
1971
+ async deleteFile(path, sessionId) {
1972
+ const session = sessionId ?? await this.ensureDefaultSession();
1973
+ return this.client.files.deleteFile(path, session);
1974
+ }
1975
+ async renameFile(oldPath, newPath, sessionId) {
1976
+ const session = sessionId ?? await this.ensureDefaultSession();
1977
+ return this.client.files.renameFile(oldPath, newPath, session);
1978
+ }
1979
+ async moveFile(sourcePath, destinationPath, sessionId) {
1980
+ const session = sessionId ?? await this.ensureDefaultSession();
1981
+ return this.client.files.moveFile(sourcePath, destinationPath, session);
1982
+ }
1983
+ async readFile(path, options = {}) {
1984
+ const session = options.sessionId ?? await this.ensureDefaultSession();
1985
+ return this.client.files.readFile(path, session, { encoding: options.encoding });
1986
+ }
1987
+ /**
1988
+ * Stream a file from the sandbox using Server-Sent Events
1989
+ * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
1990
+ * @param path - Path to the file to stream
1991
+ * @param options - Optional session ID
1992
+ */
1993
+ async readFileStream(path, options = {}) {
1994
+ const session = options.sessionId ?? await this.ensureDefaultSession();
1995
+ return this.client.files.readFileStream(path, session);
1996
+ }
1997
+ async listFiles(path, options) {
1998
+ const session = await this.ensureDefaultSession();
1999
+ return this.client.files.listFiles(path, session, options);
2000
+ }
2001
+ async exposePort(port, options) {
2002
+ if (options.hostname.endsWith(".workers.dev")) {
2003
+ const errorResponse = {
2004
+ code: ErrorCode.CUSTOM_DOMAIN_REQUIRED,
2005
+ message: `Port exposure requires a custom domain. .workers.dev domains do not support wildcard subdomains required for port proxying.`,
2006
+ context: { originalError: options.hostname },
2007
+ httpStatus: 400,
2008
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2009
+ };
2010
+ throw new CustomDomainRequiredError(errorResponse);
2011
+ }
2012
+ const sessionId = await this.ensureDefaultSession();
2013
+ await this.client.ports.exposePort(port, sessionId, options?.name);
2014
+ if (!this.sandboxName) {
2015
+ throw new Error("Sandbox name not available. Ensure sandbox is accessed through getSandbox()");
2016
+ }
2017
+ const token = this.generatePortToken();
2018
+ this.portTokens.set(port, token);
2019
+ await this.persistPortTokens();
2020
+ const url = this.constructPreviewUrl(port, this.sandboxName, options.hostname, token);
2021
+ return {
2022
+ url,
2023
+ port,
2024
+ name: options?.name
2025
+ };
2026
+ }
2027
+ async unexposePort(port) {
2028
+ if (!validatePort(port)) {
2029
+ throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
2030
+ }
2031
+ const sessionId = await this.ensureDefaultSession();
2032
+ await this.client.ports.unexposePort(port, sessionId);
2033
+ if (this.portTokens.has(port)) {
2034
+ this.portTokens.delete(port);
2035
+ await this.persistPortTokens();
2036
+ }
2037
+ }
2038
+ async getExposedPorts(hostname) {
2039
+ const sessionId = await this.ensureDefaultSession();
2040
+ const response = await this.client.ports.getExposedPorts(sessionId);
2041
+ if (!this.sandboxName) {
2042
+ throw new Error("Sandbox name not available. Ensure sandbox is accessed through getSandbox()");
2043
+ }
2044
+ return response.ports.map((port) => {
2045
+ const token = this.portTokens.get(port.port);
2046
+ if (!token) {
2047
+ throw new Error(`Port ${port.port} is exposed but has no token. This should not happen.`);
2048
+ }
2049
+ return {
2050
+ url: this.constructPreviewUrl(port.port, this.sandboxName, hostname, token),
2051
+ port: port.port,
2052
+ status: port.status
2053
+ };
2054
+ });
2055
+ }
2056
+ async isPortExposed(port) {
2057
+ try {
2058
+ const sessionId = await this.ensureDefaultSession();
2059
+ const response = await this.client.ports.getExposedPorts(sessionId);
2060
+ return response.ports.some((exposedPort) => exposedPort.port === port);
2061
+ } catch (error) {
2062
+ this.logger.error("Error checking if port is exposed", error instanceof Error ? error : new Error(String(error)), { port });
2063
+ return false;
2064
+ }
2065
+ }
2066
+ async validatePortToken(port, token) {
2067
+ const isExposed = await this.isPortExposed(port);
2068
+ if (!isExposed) {
2069
+ return false;
2070
+ }
2071
+ const storedToken = this.portTokens.get(port);
2072
+ if (!storedToken) {
2073
+ this.logger.error("Port is exposed but has no token - bug detected", void 0, { port });
2074
+ return false;
2075
+ }
2076
+ return storedToken === token;
2077
+ }
2078
+ generatePortToken() {
2079
+ const array = new Uint8Array(12);
2080
+ crypto.getRandomValues(array);
2081
+ const base64 = btoa(String.fromCharCode(...array));
2082
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "").toLowerCase();
2083
+ }
2084
+ async persistPortTokens() {
2085
+ const tokensObj = {};
2086
+ for (const [port, token] of this.portTokens.entries()) {
2087
+ tokensObj[port.toString()] = token;
2088
+ }
2089
+ await this.ctx.storage.put("portTokens", tokensObj);
2090
+ }
2091
+ constructPreviewUrl(port, sandboxId, hostname, token) {
2092
+ if (!validatePort(port)) {
2093
+ throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
2094
+ }
2095
+ const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
2096
+ const isLocalhost = isLocalhostPattern(hostname);
2097
+ if (isLocalhost) {
2098
+ const [host, portStr] = hostname.split(":");
2099
+ const mainPort = portStr || "80";
2100
+ try {
2101
+ const baseUrl = new URL(`http://${host}:${mainPort}`);
2102
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
2103
+ baseUrl.hostname = subdomainHost;
2104
+ return baseUrl.toString();
2105
+ } catch (error) {
2106
+ throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : "Unknown error"}`);
2107
+ }
2108
+ }
2109
+ try {
2110
+ const protocol = "https";
2111
+ const baseUrl = new URL(`${protocol}://${hostname}`);
2112
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
2113
+ baseUrl.hostname = subdomainHost;
2114
+ return baseUrl.toString();
2115
+ } catch (error) {
2116
+ throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : "Unknown error"}`);
2117
+ }
2118
+ }
2119
+ // ============================================================================
2120
+ // Session Management - Advanced Use Cases
2121
+ // ============================================================================
2122
+ /**
2123
+ * Create isolated execution session for advanced use cases
2124
+ * Returns ExecutionSession with full sandbox API bound to specific session
2125
+ */
2126
+ async createSession(options) {
2127
+ const sessionId = options?.id || `session-${Date.now()}`;
2128
+ await this.client.utils.createSession({
2129
+ id: sessionId,
2130
+ env: options?.env,
2131
+ cwd: options?.cwd
2132
+ });
2133
+ return this.getSessionWrapper(sessionId);
2134
+ }
2135
+ /**
2136
+ * Get an existing session by ID
2137
+ * Returns ExecutionSession wrapper bound to the specified session
2138
+ *
2139
+ * This is useful for retrieving sessions across different requests/contexts
2140
+ * without storing the ExecutionSession object (which has RPC lifecycle limitations)
2141
+ *
2142
+ * @param sessionId - The ID of an existing session
2143
+ * @returns ExecutionSession wrapper bound to the session
2144
+ */
2145
+ async getSession(sessionId) {
2146
+ return this.getSessionWrapper(sessionId);
2147
+ }
2148
+ /**
2149
+ * Internal helper to create ExecutionSession wrapper for a given sessionId
2150
+ * Used by both createSession and getSession
2151
+ */
2152
+ getSessionWrapper(sessionId) {
2153
+ return {
2154
+ id: sessionId,
2155
+ // Command execution - delegate to internal session-aware methods
2156
+ exec: (command, options) => this.execWithSession(command, sessionId, options),
2157
+ execStream: (command, options) => this.execStreamWithSession(command, sessionId, options),
2158
+ // Process management
2159
+ startProcess: (command, options) => this.startProcess(command, options, sessionId),
2160
+ listProcesses: () => this.listProcesses(sessionId),
2161
+ getProcess: (id) => this.getProcess(id, sessionId),
2162
+ killProcess: (id, signal) => this.killProcess(id, signal),
2163
+ killAllProcesses: () => this.killAllProcesses(),
2164
+ cleanupCompletedProcesses: () => this.cleanupCompletedProcesses(),
2165
+ getProcessLogs: (id) => this.getProcessLogs(id),
2166
+ streamProcessLogs: (processId, options) => this.streamProcessLogs(processId, options),
2167
+ // File operations - pass sessionId via options or parameter
2168
+ writeFile: (path, content, options) => this.writeFile(path, content, { ...options, sessionId }),
2169
+ readFile: (path, options) => this.readFile(path, { ...options, sessionId }),
2170
+ readFileStream: (path) => this.readFileStream(path, { sessionId }),
2171
+ mkdir: (path, options) => this.mkdir(path, { ...options, sessionId }),
2172
+ deleteFile: (path) => this.deleteFile(path, sessionId),
2173
+ renameFile: (oldPath, newPath) => this.renameFile(oldPath, newPath, sessionId),
2174
+ moveFile: (sourcePath, destPath) => this.moveFile(sourcePath, destPath, sessionId),
2175
+ listFiles: (path, options) => this.client.files.listFiles(path, sessionId, options),
2176
+ // Git operations
2177
+ gitCheckout: (repoUrl, options) => this.gitCheckout(repoUrl, { ...options, sessionId }),
2178
+ // Environment management - needs special handling
2179
+ setEnvVars: async (envVars) => {
2180
+ try {
2181
+ for (const [key, value] of Object.entries(envVars)) {
2182
+ const escapedValue = value.replace(/'/g, "'\\''");
2183
+ const exportCommand = `export ${key}='${escapedValue}'`;
2184
+ const result = await this.client.commands.execute(exportCommand, sessionId);
2185
+ if (result.exitCode !== 0) {
2186
+ throw new Error(`Failed to set ${key}: ${result.stderr || "Unknown error"}`);
2187
+ }
2188
+ }
2189
+ } catch (error) {
2190
+ this.logger.error("Failed to set environment variables", error instanceof Error ? error : new Error(String(error)), { sessionId });
2191
+ throw error;
2192
+ }
2193
+ },
2194
+ // Code interpreter methods - delegate to sandbox's code interpreter
2195
+ createCodeContext: (options) => this.codeInterpreter.createCodeContext(options),
2196
+ runCode: async (code, options) => {
2197
+ const execution = await this.codeInterpreter.runCode(code, options);
2198
+ return execution.toJSON();
2199
+ },
2200
+ runCodeStream: (code, options) => this.codeInterpreter.runCodeStream(code, options),
2201
+ listCodeContexts: () => this.codeInterpreter.listCodeContexts(),
2202
+ deleteCodeContext: (contextId) => this.codeInterpreter.deleteCodeContext(contextId)
2203
+ };
2204
+ }
2205
+ // ============================================================================
2206
+ // Code interpreter methods - delegate to CodeInterpreter wrapper
2207
+ // ============================================================================
2208
+ async createCodeContext(options) {
2209
+ return this.codeInterpreter.createCodeContext(options);
2210
+ }
2211
+ async runCode(code, options) {
2212
+ const execution = await this.codeInterpreter.runCode(code, options);
2213
+ return execution.toJSON();
2214
+ }
2215
+ async runCodeStream(code, options) {
2216
+ return this.codeInterpreter.runCodeStream(code, options);
2217
+ }
2218
+ async listCodeContexts() {
2219
+ return this.codeInterpreter.listCodeContexts();
2220
+ }
2221
+ async deleteCodeContext(contextId) {
2222
+ return this.codeInterpreter.deleteCodeContext(contextId);
2223
+ }
2224
+ };
2225
+
2226
+ // src/request-handler.ts
2227
+ async function proxyToSandbox(request, env) {
2228
+ const traceId = TraceContext.fromHeaders(request.headers) || TraceContext.generate();
2229
+ const logger = createLogger({
2230
+ component: "sandbox-do",
2231
+ traceId,
2232
+ operation: "proxy"
2233
+ });
2234
+ try {
2235
+ const url = new URL(request.url);
2236
+ const routeInfo = extractSandboxRoute(url);
2237
+ if (!routeInfo) {
2238
+ return null;
2239
+ }
2240
+ const { sandboxId, port, path, token } = routeInfo;
2241
+ const sandbox = getSandbox(env.Sandbox, sandboxId);
2242
+ if (port !== 3e3) {
2243
+ const isValidToken = await sandbox.validatePortToken(port, token);
2244
+ if (!isValidToken) {
2245
+ logger.warn("Invalid token access blocked", {
2246
+ port,
2247
+ sandboxId,
2248
+ path,
2249
+ hostname: url.hostname,
2250
+ url: request.url,
2251
+ method: request.method,
2252
+ userAgent: request.headers.get("User-Agent") || "unknown"
2253
+ });
2254
+ return new Response(
2255
+ JSON.stringify({
2256
+ error: `Access denied: Invalid token or port not exposed`,
2257
+ code: "INVALID_TOKEN"
2258
+ }),
2259
+ {
2260
+ status: 404,
2261
+ headers: {
2262
+ "Content-Type": "application/json"
2263
+ }
2264
+ }
2265
+ );
2266
+ }
2267
+ }
2268
+ let proxyUrl;
2269
+ if (port !== 3e3) {
2270
+ proxyUrl = `http://localhost:${port}${path}${url.search}`;
2271
+ } else {
2272
+ proxyUrl = `http://localhost:3000${path}${url.search}`;
2273
+ }
2274
+ const proxyRequest = new Request(proxyUrl, {
2275
+ method: request.method,
2276
+ headers: {
2277
+ ...Object.fromEntries(request.headers),
2278
+ "X-Original-URL": request.url,
2279
+ "X-Forwarded-Host": url.hostname,
2280
+ "X-Forwarded-Proto": url.protocol.replace(":", ""),
2281
+ "X-Sandbox-Name": sandboxId
2282
+ // Pass the friendly name
2283
+ },
2284
+ body: request.body,
2285
+ // @ts-expect-error - duplex required for body streaming in modern runtimes
2286
+ duplex: "half"
2287
+ });
2288
+ return sandbox.containerFetch(proxyRequest, port);
2289
+ } catch (error) {
2290
+ logger.error("Proxy routing error", error instanceof Error ? error : new Error(String(error)));
2291
+ return new Response("Proxy routing error", { status: 500 });
2292
+ }
2293
+ }
2294
+ function extractSandboxRoute(url) {
2295
+ const subdomainMatch = url.hostname.match(/^(\d{4,5})-([^.-][^.]*[^.-]|[^.-])-([a-zA-Z0-9_-]{12,20})\.(.+)$/);
2296
+ if (!subdomainMatch) {
2297
+ return null;
2298
+ }
2299
+ const portStr = subdomainMatch[1];
2300
+ const sandboxId = subdomainMatch[2];
2301
+ const token = subdomainMatch[3];
2302
+ const domain = subdomainMatch[4];
2303
+ const port = parseInt(portStr, 10);
2304
+ if (!validatePort(port)) {
2305
+ return null;
2306
+ }
2307
+ let sanitizedSandboxId;
2308
+ try {
2309
+ sanitizedSandboxId = sanitizeSandboxId(sandboxId);
2310
+ } catch (error) {
2311
+ return null;
2312
+ }
2313
+ if (sandboxId.length > 63) {
2314
+ return null;
2315
+ }
2316
+ return {
2317
+ port,
2318
+ sandboxId: sanitizedSandboxId,
2319
+ path: url.pathname || "/",
2320
+ token
2321
+ };
2322
+ }
2323
+ function isLocalhostPattern(hostname) {
2324
+ if (hostname.startsWith("[")) {
2325
+ if (hostname.includes("]:")) {
2326
+ const ipv6Part = hostname.substring(0, hostname.indexOf("]:") + 1);
2327
+ return ipv6Part === "[::1]";
2328
+ } else {
2329
+ return hostname === "[::1]";
2330
+ }
2331
+ }
2332
+ if (hostname === "::1") {
2333
+ return true;
2334
+ }
2335
+ const hostPart = hostname.split(":")[0];
2336
+ return hostPart === "localhost" || hostPart === "127.0.0.1" || hostPart === "0.0.0.0";
2337
+ }
2338
+
2339
+ export {
2340
+ CommandClient,
2341
+ FileClient,
2342
+ GitClient,
2343
+ PortClient,
2344
+ ProcessClient,
2345
+ UtilityClient,
2346
+ SandboxClient,
2347
+ proxyToSandbox,
2348
+ isLocalhostPattern,
2349
+ getSandbox,
2350
+ Sandbox
2351
+ };
2352
+ //# sourceMappingURL=chunk-53JFOF7F.js.map