@cloudflare/sandbox 0.3.6 → 0.4.1

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