@cloudflare/sandbox 0.0.0-d86b60e → 0.0.0-da2cfb8

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