@cloudflare/sandbox 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +2 -2
- package/CHANGELOG.md +6 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/version.ts +1 -1
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
> @cloudflare/sandbox@0.5.
|
|
2
|
+
> @cloudflare/sandbox@0.5.4 build
|
|
3
3
|
> rm -rf dist && tsdown --config tsdown.config.ts
|
|
4
4
|
|
|
5
5
|
[34mℹ[39m tsdown [2mv0.16.6[22m powered by rolldown [2mv1.0.0-beta.51[22m
|
|
@@ -20,4 +20,4 @@
|
|
|
20
20
|
[34mℹ[39m [2mdist/[22m[32m[1mopenai/index.d.ts[22m[39m [2m 2.10 kB[22m [2m│ gzip: 0.81 kB[22m
|
|
21
21
|
[34mℹ[39m [2mdist/[22m[32msandbox-HQazw9bn.d.ts[39m [2m 51.36 kB[22m [2m│ gzip: 11.79 kB[22m
|
|
22
22
|
[34mℹ[39m 12 files, total: 536.66 kB
|
|
23
|
-
[32m✔[39m Build complete in [
|
|
23
|
+
[32m✔[39m Build complete in [32m4464ms[39m
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @cloudflare/sandbox
|
|
2
2
|
|
|
3
|
+
## 0.5.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#243](https://github.com/cloudflare/sandbox-sdk/pull/243) [`32a0dab`](https://github.com/cloudflare/sandbox-sdk/commit/32a0dab89375aa238a97b9d213234236fd364195) Thanks [@whoiskatrin](https://github.com/whoiskatrin)! - add getFileMetadata method in FileService to get only metadata
|
|
8
|
+
|
|
3
9
|
## 0.5.3
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/dist/index.js
CHANGED
|
@@ -2055,7 +2055,7 @@ function resolveS3fsOptions(provider, userOptions) {
|
|
|
2055
2055
|
* This file is auto-updated by .github/changeset-version.ts during releases
|
|
2056
2056
|
* DO NOT EDIT MANUALLY - Changes will be overwritten on the next version bump
|
|
2057
2057
|
*/
|
|
2058
|
-
const SDK_VERSION = "0.5.
|
|
2058
|
+
const SDK_VERSION = "0.5.4";
|
|
2059
2059
|
|
|
2060
2060
|
//#endregion
|
|
2061
2061
|
//#region src/sandbox.ts
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["errorResponse: ErrorResponse<TContext>","errorData: NewErrorResponse","data: ExecuteRequest","data: GitCheckoutRequest","lastError: Error | undefined","data: StartProcessRequest","clientOptions: HttpClientOptions","code?: string","proxyUrl: string","sanitizedSandboxId: string","provider: BucketProvider | null","s3fsArgs: string[]","request: Request","port: number | undefined","error: unknown","result: ExecResult","tokensObj: Record<string, string>","metadata: FileMetadata | null","chunks: Array<string | Uint8Array>"],"sources":["../../shared/dist/errors/codes.js","../../shared/dist/errors/status-map.js","../src/errors/classes.ts","../src/errors/adapter.ts","../src/clients/base-client.ts","../src/clients/command-client.ts","../src/clients/file-client.ts","../src/clients/git-client.ts","../src/clients/interpreter-client.ts","../src/clients/port-client.ts","../src/clients/process-client.ts","../src/clients/utility-client.ts","../src/clients/sandbox-client.ts","../src/security.ts","../src/interpreter.ts","../src/request-handler.ts","../src/sse-parser.ts","../src/storage-mount/errors.ts","../src/storage-mount/credential-detection.ts","../src/storage-mount/provider-detection.ts","../src/version.ts","../src/sandbox.ts","../src/file-stream.ts"],"sourcesContent":["/**\n * Centralized error code registry\n * Each code maps to a specific error type with consistent semantics\n */\nexport const ErrorCode = {\n // File System Errors (404)\n FILE_NOT_FOUND: 'FILE_NOT_FOUND',\n // Permission Errors (403)\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n // File System Errors (409)\n FILE_EXISTS: 'FILE_EXISTS',\n // File System Errors (400)\n IS_DIRECTORY: 'IS_DIRECTORY',\n NOT_DIRECTORY: 'NOT_DIRECTORY',\n // File System Errors (500)\n NO_SPACE: 'NO_SPACE',\n TOO_MANY_FILES: 'TOO_MANY_FILES',\n RESOURCE_BUSY: 'RESOURCE_BUSY',\n READ_ONLY: 'READ_ONLY',\n NAME_TOO_LONG: 'NAME_TOO_LONG',\n TOO_MANY_LINKS: 'TOO_MANY_LINKS',\n FILESYSTEM_ERROR: 'FILESYSTEM_ERROR',\n // Command Errors (404)\n COMMAND_NOT_FOUND: 'COMMAND_NOT_FOUND',\n // Command Errors (403/400)\n COMMAND_PERMISSION_DENIED: 'COMMAND_PERMISSION_DENIED',\n INVALID_COMMAND: 'INVALID_COMMAND',\n // Command Errors (500)\n COMMAND_EXECUTION_ERROR: 'COMMAND_EXECUTION_ERROR',\n STREAM_START_ERROR: 'STREAM_START_ERROR',\n // Process Errors (404)\n PROCESS_NOT_FOUND: 'PROCESS_NOT_FOUND',\n // Process Errors (403/500)\n PROCESS_PERMISSION_DENIED: 'PROCESS_PERMISSION_DENIED',\n PROCESS_ERROR: 'PROCESS_ERROR',\n // Port Errors (409)\n PORT_ALREADY_EXPOSED: 'PORT_ALREADY_EXPOSED',\n PORT_IN_USE: 'PORT_IN_USE',\n // Port Errors (404)\n PORT_NOT_EXPOSED: 'PORT_NOT_EXPOSED',\n // Port Errors (400)\n INVALID_PORT_NUMBER: 'INVALID_PORT_NUMBER',\n INVALID_PORT: 'INVALID_PORT',\n // Port Errors (502/500)\n SERVICE_NOT_RESPONDING: 'SERVICE_NOT_RESPONDING',\n PORT_OPERATION_ERROR: 'PORT_OPERATION_ERROR',\n // Port Errors (400)\n CUSTOM_DOMAIN_REQUIRED: 'CUSTOM_DOMAIN_REQUIRED',\n // Git Errors (404)\n GIT_REPOSITORY_NOT_FOUND: 'GIT_REPOSITORY_NOT_FOUND',\n GIT_BRANCH_NOT_FOUND: 'GIT_BRANCH_NOT_FOUND',\n // Git Errors (401)\n GIT_AUTH_FAILED: 'GIT_AUTH_FAILED',\n // Git Errors (502)\n GIT_NETWORK_ERROR: 'GIT_NETWORK_ERROR',\n // Git Errors (400)\n INVALID_GIT_URL: 'INVALID_GIT_URL',\n // Git Errors (500)\n GIT_CLONE_FAILED: 'GIT_CLONE_FAILED',\n GIT_CHECKOUT_FAILED: 'GIT_CHECKOUT_FAILED',\n GIT_OPERATION_FAILED: 'GIT_OPERATION_FAILED',\n // Bucket mounting errors\n BUCKET_MOUNT_ERROR: 'BUCKET_MOUNT_ERROR',\n S3FS_MOUNT_ERROR: 'S3FS_MOUNT_ERROR',\n MISSING_CREDENTIALS: 'MISSING_CREDENTIALS',\n INVALID_MOUNT_CONFIG: 'INVALID_MOUNT_CONFIG',\n // Code Interpreter Errors (503)\n INTERPRETER_NOT_READY: 'INTERPRETER_NOT_READY',\n // Code Interpreter Errors (404)\n CONTEXT_NOT_FOUND: 'CONTEXT_NOT_FOUND',\n // Code Interpreter Errors (500)\n CODE_EXECUTION_ERROR: 'CODE_EXECUTION_ERROR',\n // Validation Errors (400)\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n // Generic Errors (400/500)\n INVALID_JSON_RESPONSE: 'INVALID_JSON_RESPONSE',\n UNKNOWN_ERROR: 'UNKNOWN_ERROR',\n INTERNAL_ERROR: 'INTERNAL_ERROR'\n};\n","import { ErrorCode } from './codes';\n/**\n * Maps error codes to HTTP status codes\n * Centralized mapping ensures consistency across SDK\n */\nexport const ERROR_STATUS_MAP = {\n // 404 Not Found\n [ErrorCode.FILE_NOT_FOUND]: 404,\n [ErrorCode.COMMAND_NOT_FOUND]: 404,\n [ErrorCode.PROCESS_NOT_FOUND]: 404,\n [ErrorCode.PORT_NOT_EXPOSED]: 404,\n [ErrorCode.GIT_REPOSITORY_NOT_FOUND]: 404,\n [ErrorCode.GIT_BRANCH_NOT_FOUND]: 404,\n [ErrorCode.CONTEXT_NOT_FOUND]: 404,\n // 400 Bad Request\n [ErrorCode.IS_DIRECTORY]: 400,\n [ErrorCode.NOT_DIRECTORY]: 400,\n [ErrorCode.INVALID_COMMAND]: 400,\n [ErrorCode.INVALID_PORT_NUMBER]: 400,\n [ErrorCode.INVALID_PORT]: 400,\n [ErrorCode.INVALID_GIT_URL]: 400,\n [ErrorCode.CUSTOM_DOMAIN_REQUIRED]: 400,\n [ErrorCode.INVALID_JSON_RESPONSE]: 400,\n [ErrorCode.NAME_TOO_LONG]: 400,\n [ErrorCode.VALIDATION_FAILED]: 400,\n [ErrorCode.MISSING_CREDENTIALS]: 400,\n [ErrorCode.INVALID_MOUNT_CONFIG]: 400,\n // 401 Unauthorized\n [ErrorCode.GIT_AUTH_FAILED]: 401,\n // 403 Forbidden\n [ErrorCode.PERMISSION_DENIED]: 403,\n [ErrorCode.COMMAND_PERMISSION_DENIED]: 403,\n [ErrorCode.PROCESS_PERMISSION_DENIED]: 403,\n [ErrorCode.READ_ONLY]: 403,\n // 409 Conflict\n [ErrorCode.FILE_EXISTS]: 409,\n [ErrorCode.PORT_ALREADY_EXPOSED]: 409,\n [ErrorCode.PORT_IN_USE]: 409,\n [ErrorCode.RESOURCE_BUSY]: 409,\n // 502 Bad Gateway\n [ErrorCode.SERVICE_NOT_RESPONDING]: 502,\n [ErrorCode.GIT_NETWORK_ERROR]: 502,\n // 503 Service Unavailable\n [ErrorCode.INTERPRETER_NOT_READY]: 503,\n // 500 Internal Server Error\n [ErrorCode.NO_SPACE]: 500,\n [ErrorCode.TOO_MANY_FILES]: 500,\n [ErrorCode.TOO_MANY_LINKS]: 500,\n [ErrorCode.FILESYSTEM_ERROR]: 500,\n [ErrorCode.COMMAND_EXECUTION_ERROR]: 500,\n [ErrorCode.STREAM_START_ERROR]: 500,\n [ErrorCode.PROCESS_ERROR]: 500,\n [ErrorCode.PORT_OPERATION_ERROR]: 500,\n [ErrorCode.GIT_CLONE_FAILED]: 500,\n [ErrorCode.GIT_CHECKOUT_FAILED]: 500,\n [ErrorCode.GIT_OPERATION_FAILED]: 500,\n [ErrorCode.CODE_EXECUTION_ERROR]: 500,\n [ErrorCode.BUCKET_MOUNT_ERROR]: 500,\n [ErrorCode.S3FS_MOUNT_ERROR]: 500,\n [ErrorCode.UNKNOWN_ERROR]: 500,\n [ErrorCode.INTERNAL_ERROR]: 500\n};\n/**\n * Get HTTP status code for an error code\n * Falls back to 500 for unknown errors\n */\nexport function getHttpStatus(code) {\n return ERROR_STATUS_MAP[code] || 500;\n}\n","/**\n * Type-safe error classes that wrap ErrorResponse from container\n *\n * All error classes extend SandboxError<TContext> which wraps the full ErrorResponse\n * and provides type-safe accessors for error properties.\n */\n\nimport type {\n CodeExecutionContext,\n CommandErrorContext,\n CommandNotFoundContext,\n ContextNotFoundContext,\n ErrorResponse,\n FileExistsContext,\n FileNotFoundContext,\n FileSystemContext,\n GitAuthFailedContext,\n GitBranchNotFoundContext,\n GitErrorContext,\n GitRepositoryNotFoundContext,\n InternalErrorContext,\n InterpreterNotReadyContext,\n InvalidPortContext,\n PortAlreadyExposedContext,\n PortErrorContext,\n PortNotExposedContext,\n ProcessErrorContext,\n ProcessNotFoundContext,\n ValidationFailedContext\n} from '@repo/shared/errors';\n\n/**\n * Base SDK error that wraps ErrorResponse\n * Preserves all error information from container\n */\nexport class SandboxError<TContext = Record<string, unknown>> extends Error {\n constructor(public readonly errorResponse: ErrorResponse<TContext>) {\n super(errorResponse.message);\n this.name = 'SandboxError';\n }\n\n // Convenience accessors\n get code() {\n return this.errorResponse.code;\n }\n get context() {\n return this.errorResponse.context;\n }\n get httpStatus() {\n return this.errorResponse.httpStatus;\n }\n get operation() {\n return this.errorResponse.operation;\n }\n get suggestion() {\n return this.errorResponse.suggestion;\n }\n get timestamp() {\n return this.errorResponse.timestamp;\n }\n get documentation() {\n return this.errorResponse.documentation;\n }\n\n // Custom serialization for logging\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n context: this.context,\n httpStatus: this.httpStatus,\n operation: this.operation,\n suggestion: this.suggestion,\n timestamp: this.timestamp,\n documentation: this.documentation,\n stack: this.stack\n };\n }\n}\n\n// ============================================================================\n// File System Errors\n// ============================================================================\n\n/**\n * Error thrown when a file or directory is not found\n */\nexport class FileNotFoundError extends SandboxError<FileNotFoundContext> {\n constructor(errorResponse: ErrorResponse<FileNotFoundContext>) {\n super(errorResponse);\n this.name = 'FileNotFoundError';\n }\n\n // Type-safe accessors\n get path() {\n return this.context.path;\n }\n}\n\n/**\n * Error thrown when a file already exists\n */\nexport class FileExistsError extends SandboxError<FileExistsContext> {\n constructor(errorResponse: ErrorResponse<FileExistsContext>) {\n super(errorResponse);\n this.name = 'FileExistsError';\n }\n\n // Type-safe accessor\n get path() {\n return this.context.path;\n }\n}\n\n/**\n * Generic file system error (permissions, disk full, etc.)\n */\nexport class FileSystemError extends SandboxError<FileSystemContext> {\n constructor(errorResponse: ErrorResponse<FileSystemContext>) {\n super(errorResponse);\n this.name = 'FileSystemError';\n }\n\n // Type-safe accessors\n get path() {\n return this.context.path;\n }\n get stderr() {\n return this.context.stderr;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n}\n\n/**\n * Error thrown when permission is denied\n */\nexport class PermissionDeniedError extends SandboxError<FileSystemContext> {\n constructor(errorResponse: ErrorResponse<FileSystemContext>) {\n super(errorResponse);\n this.name = 'PermissionDeniedError';\n }\n\n get path() {\n return this.context.path;\n }\n}\n\n// ============================================================================\n// Command Errors\n// ============================================================================\n\n/**\n * Error thrown when a command is not found\n */\nexport class CommandNotFoundError extends SandboxError<CommandNotFoundContext> {\n constructor(errorResponse: ErrorResponse<CommandNotFoundContext>) {\n super(errorResponse);\n this.name = 'CommandNotFoundError';\n }\n\n // Type-safe accessor\n get command() {\n return this.context.command;\n }\n}\n\n/**\n * Generic command execution error\n */\nexport class CommandError extends SandboxError<CommandErrorContext> {\n constructor(errorResponse: ErrorResponse<CommandErrorContext>) {\n super(errorResponse);\n this.name = 'CommandError';\n }\n\n // Type-safe accessors\n get command() {\n return this.context.command;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n get stdout() {\n return this.context.stdout;\n }\n get stderr() {\n return this.context.stderr;\n }\n}\n\n// ============================================================================\n// Process Errors\n// ============================================================================\n\n/**\n * Error thrown when a process is not found\n */\nexport class ProcessNotFoundError extends SandboxError<ProcessNotFoundContext> {\n constructor(errorResponse: ErrorResponse<ProcessNotFoundContext>) {\n super(errorResponse);\n this.name = 'ProcessNotFoundError';\n }\n\n // Type-safe accessor\n get processId() {\n return this.context.processId;\n }\n}\n\n/**\n * Generic process error\n */\nexport class ProcessError extends SandboxError<ProcessErrorContext> {\n constructor(errorResponse: ErrorResponse<ProcessErrorContext>) {\n super(errorResponse);\n this.name = 'ProcessError';\n }\n\n // Type-safe accessors\n get processId() {\n return this.context.processId;\n }\n get pid() {\n return this.context.pid;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n get stderr() {\n return this.context.stderr;\n }\n}\n\n// ============================================================================\n// Port Errors\n// ============================================================================\n\n/**\n * Error thrown when a port is already exposed\n */\nexport class PortAlreadyExposedError extends SandboxError<PortAlreadyExposedContext> {\n constructor(errorResponse: ErrorResponse<PortAlreadyExposedContext>) {\n super(errorResponse);\n this.name = 'PortAlreadyExposedError';\n }\n\n // Type-safe accessors\n get port() {\n return this.context.port;\n }\n get portName() {\n return this.context.portName;\n }\n}\n\n/**\n * Error thrown when a port is not exposed\n */\nexport class PortNotExposedError extends SandboxError<PortNotExposedContext> {\n constructor(errorResponse: ErrorResponse<PortNotExposedContext>) {\n super(errorResponse);\n this.name = 'PortNotExposedError';\n }\n\n // Type-safe accessor\n get port() {\n return this.context.port;\n }\n}\n\n/**\n * Error thrown when a port number is invalid\n */\nexport class InvalidPortError extends SandboxError<InvalidPortContext> {\n constructor(errorResponse: ErrorResponse<InvalidPortContext>) {\n super(errorResponse);\n this.name = 'InvalidPortError';\n }\n\n // Type-safe accessors\n get port() {\n return this.context.port;\n }\n get reason() {\n return this.context.reason;\n }\n}\n\n/**\n * Error thrown when a service on a port is not responding\n */\nexport class ServiceNotRespondingError extends SandboxError<PortErrorContext> {\n constructor(errorResponse: ErrorResponse<PortErrorContext>) {\n super(errorResponse);\n this.name = 'ServiceNotRespondingError';\n }\n\n // Type-safe accessors\n get port() {\n return this.context.port;\n }\n get portName() {\n return this.context.portName;\n }\n}\n\n/**\n * Error thrown when a port is already in use\n */\nexport class PortInUseError extends SandboxError<PortErrorContext> {\n constructor(errorResponse: ErrorResponse<PortErrorContext>) {\n super(errorResponse);\n this.name = 'PortInUseError';\n }\n\n // Type-safe accessor\n get port() {\n return this.context.port;\n }\n}\n\n/**\n * Generic port operation error\n */\nexport class PortError extends SandboxError<PortErrorContext> {\n constructor(errorResponse: ErrorResponse<PortErrorContext>) {\n super(errorResponse);\n this.name = 'PortError';\n }\n\n // Type-safe accessors\n get port() {\n return this.context.port;\n }\n get portName() {\n return this.context.portName;\n }\n get stderr() {\n return this.context.stderr;\n }\n}\n\n/**\n * Error thrown when port exposure requires a custom domain\n */\nexport class CustomDomainRequiredError extends SandboxError<InternalErrorContext> {\n constructor(errorResponse: ErrorResponse<InternalErrorContext>) {\n super(errorResponse);\n this.name = 'CustomDomainRequiredError';\n }\n}\n\n// ============================================================================\n// Git Errors\n// ============================================================================\n\n/**\n * Error thrown when a git repository is not found\n */\nexport class GitRepositoryNotFoundError extends SandboxError<GitRepositoryNotFoundContext> {\n constructor(errorResponse: ErrorResponse<GitRepositoryNotFoundContext>) {\n super(errorResponse);\n this.name = 'GitRepositoryNotFoundError';\n }\n\n // Type-safe accessor\n get repository() {\n return this.context.repository;\n }\n}\n\n/**\n * Error thrown when git authentication fails\n */\nexport class GitAuthenticationError extends SandboxError<GitAuthFailedContext> {\n constructor(errorResponse: ErrorResponse<GitAuthFailedContext>) {\n super(errorResponse);\n this.name = 'GitAuthenticationError';\n }\n\n // Type-safe accessor\n get repository() {\n return this.context.repository;\n }\n}\n\n/**\n * Error thrown when a git branch is not found\n */\nexport class GitBranchNotFoundError extends SandboxError<GitBranchNotFoundContext> {\n constructor(errorResponse: ErrorResponse<GitBranchNotFoundContext>) {\n super(errorResponse);\n this.name = 'GitBranchNotFoundError';\n }\n\n // Type-safe accessors\n get branch() {\n return this.context.branch;\n }\n get repository() {\n return this.context.repository;\n }\n}\n\n/**\n * Error thrown when a git network operation fails\n */\nexport class GitNetworkError extends SandboxError<GitErrorContext> {\n constructor(errorResponse: ErrorResponse<GitErrorContext>) {\n super(errorResponse);\n this.name = 'GitNetworkError';\n }\n\n // Type-safe accessors\n get repository() {\n return this.context.repository;\n }\n get branch() {\n return this.context.branch;\n }\n get targetDir() {\n return this.context.targetDir;\n }\n}\n\n/**\n * Error thrown when git clone fails\n */\nexport class GitCloneError extends SandboxError<GitErrorContext> {\n constructor(errorResponse: ErrorResponse<GitErrorContext>) {\n super(errorResponse);\n this.name = 'GitCloneError';\n }\n\n // Type-safe accessors\n get repository() {\n return this.context.repository;\n }\n get targetDir() {\n return this.context.targetDir;\n }\n get stderr() {\n return this.context.stderr;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n}\n\n/**\n * Error thrown when git checkout fails\n */\nexport class GitCheckoutError extends SandboxError<GitErrorContext> {\n constructor(errorResponse: ErrorResponse<GitErrorContext>) {\n super(errorResponse);\n this.name = 'GitCheckoutError';\n }\n\n // Type-safe accessors\n get branch() {\n return this.context.branch;\n }\n get repository() {\n return this.context.repository;\n }\n get stderr() {\n return this.context.stderr;\n }\n}\n\n/**\n * Error thrown when a git URL is invalid\n */\nexport class InvalidGitUrlError extends SandboxError<ValidationFailedContext> {\n constructor(errorResponse: ErrorResponse<ValidationFailedContext>) {\n super(errorResponse);\n this.name = 'InvalidGitUrlError';\n }\n\n // Type-safe accessor\n get validationErrors() {\n return this.context.validationErrors;\n }\n}\n\n/**\n * Generic git operation error\n */\nexport class GitError extends SandboxError<GitErrorContext> {\n constructor(errorResponse: ErrorResponse<GitErrorContext>) {\n super(errorResponse);\n this.name = 'GitError';\n }\n\n // Type-safe accessors\n get repository() {\n return this.context.repository;\n }\n get branch() {\n return this.context.branch;\n }\n get targetDir() {\n return this.context.targetDir;\n }\n get stderr() {\n return this.context.stderr;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n}\n\n// ============================================================================\n// Code Interpreter Errors\n// ============================================================================\n\n/**\n * Error thrown when interpreter is not ready\n */\nexport class InterpreterNotReadyError extends SandboxError<InterpreterNotReadyContext> {\n constructor(errorResponse: ErrorResponse<InterpreterNotReadyContext>) {\n super(errorResponse);\n this.name = 'InterpreterNotReadyError';\n }\n\n // Type-safe accessors\n get retryAfter() {\n return this.context.retryAfter;\n }\n get progress() {\n return this.context.progress;\n }\n}\n\n/**\n * Error thrown when a context is not found\n */\nexport class ContextNotFoundError extends SandboxError<ContextNotFoundContext> {\n constructor(errorResponse: ErrorResponse<ContextNotFoundContext>) {\n super(errorResponse);\n this.name = 'ContextNotFoundError';\n }\n\n // Type-safe accessor\n get contextId() {\n return this.context.contextId;\n }\n}\n\n/**\n * Error thrown when code execution fails\n */\nexport class CodeExecutionError extends SandboxError<CodeExecutionContext> {\n constructor(errorResponse: ErrorResponse<CodeExecutionContext>) {\n super(errorResponse);\n this.name = 'CodeExecutionError';\n }\n\n // Type-safe accessors\n get contextId() {\n return this.context.contextId;\n }\n get ename() {\n return this.context.ename;\n }\n get evalue() {\n return this.context.evalue;\n }\n get traceback() {\n return this.context.traceback;\n }\n}\n\n// ============================================================================\n// Validation Errors\n// ============================================================================\n\n/**\n * Error thrown when validation fails\n */\nexport class ValidationFailedError extends SandboxError<ValidationFailedContext> {\n constructor(errorResponse: ErrorResponse<ValidationFailedContext>) {\n super(errorResponse);\n this.name = 'ValidationFailedError';\n }\n\n // Type-safe accessor\n get validationErrors() {\n return this.context.validationErrors;\n }\n}\n","/**\n * Error adapter that converts ErrorResponse to appropriate Error class\n *\n * Simple switch statement - we trust the container sends correct context\n * No validation overhead since we control both sides\n */\n\nimport type {\n CodeExecutionContext,\n CommandErrorContext,\n CommandNotFoundContext,\n ContextNotFoundContext,\n ErrorResponse,\n FileExistsContext,\n FileNotFoundContext,\n FileSystemContext,\n GitAuthFailedContext,\n GitBranchNotFoundContext,\n GitErrorContext,\n GitRepositoryNotFoundContext,\n InternalErrorContext,\n InterpreterNotReadyContext,\n InvalidPortContext,\n PortAlreadyExposedContext,\n PortErrorContext,\n PortNotExposedContext,\n ProcessErrorContext,\n ProcessNotFoundContext,\n ValidationFailedContext\n} from '@repo/shared/errors';\nimport { ErrorCode } from '@repo/shared/errors';\n\nimport {\n CodeExecutionError,\n CommandError,\n CommandNotFoundError,\n ContextNotFoundError,\n CustomDomainRequiredError,\n FileExistsError,\n FileNotFoundError,\n FileSystemError,\n GitAuthenticationError,\n GitBranchNotFoundError,\n GitCheckoutError,\n GitCloneError,\n GitError,\n GitNetworkError,\n GitRepositoryNotFoundError,\n InterpreterNotReadyError,\n InvalidGitUrlError,\n InvalidPortError,\n PermissionDeniedError,\n PortAlreadyExposedError,\n PortError,\n PortInUseError,\n PortNotExposedError,\n ProcessError,\n ProcessNotFoundError,\n SandboxError,\n ServiceNotRespondingError,\n ValidationFailedError\n} from './classes';\n\n/**\n * Convert ErrorResponse to appropriate Error class\n * Simple switch statement - we trust the container sends correct context\n */\nexport function createErrorFromResponse(errorResponse: ErrorResponse): Error {\n // We trust the container sends correct context, use type assertions\n switch (errorResponse.code) {\n // File System Errors\n case ErrorCode.FILE_NOT_FOUND:\n return new FileNotFoundError(\n errorResponse as unknown as ErrorResponse<FileNotFoundContext>\n );\n\n case ErrorCode.FILE_EXISTS:\n return new FileExistsError(\n errorResponse as unknown as ErrorResponse<FileExistsContext>\n );\n\n case ErrorCode.PERMISSION_DENIED:\n return new PermissionDeniedError(\n errorResponse as unknown as ErrorResponse<FileSystemContext>\n );\n\n case ErrorCode.IS_DIRECTORY:\n case ErrorCode.NOT_DIRECTORY:\n case ErrorCode.NO_SPACE:\n case ErrorCode.TOO_MANY_FILES:\n case ErrorCode.RESOURCE_BUSY:\n case ErrorCode.READ_ONLY:\n case ErrorCode.NAME_TOO_LONG:\n case ErrorCode.TOO_MANY_LINKS:\n case ErrorCode.FILESYSTEM_ERROR:\n return new FileSystemError(\n errorResponse as unknown as ErrorResponse<FileSystemContext>\n );\n\n // Command Errors\n case ErrorCode.COMMAND_NOT_FOUND:\n return new CommandNotFoundError(\n errorResponse as unknown as ErrorResponse<CommandNotFoundContext>\n );\n\n case ErrorCode.COMMAND_PERMISSION_DENIED:\n case ErrorCode.COMMAND_EXECUTION_ERROR:\n case ErrorCode.INVALID_COMMAND:\n case ErrorCode.STREAM_START_ERROR:\n return new CommandError(\n errorResponse as unknown as ErrorResponse<CommandErrorContext>\n );\n\n // Process Errors\n case ErrorCode.PROCESS_NOT_FOUND:\n return new ProcessNotFoundError(\n errorResponse as unknown as ErrorResponse<ProcessNotFoundContext>\n );\n\n case ErrorCode.PROCESS_PERMISSION_DENIED:\n case ErrorCode.PROCESS_ERROR:\n return new ProcessError(\n errorResponse as unknown as ErrorResponse<ProcessErrorContext>\n );\n\n // Port Errors\n case ErrorCode.PORT_ALREADY_EXPOSED:\n return new PortAlreadyExposedError(\n errorResponse as unknown as ErrorResponse<PortAlreadyExposedContext>\n );\n\n case ErrorCode.PORT_NOT_EXPOSED:\n return new PortNotExposedError(\n errorResponse as unknown as ErrorResponse<PortNotExposedContext>\n );\n\n case ErrorCode.INVALID_PORT_NUMBER:\n case ErrorCode.INVALID_PORT:\n return new InvalidPortError(\n errorResponse as unknown as ErrorResponse<InvalidPortContext>\n );\n\n case ErrorCode.SERVICE_NOT_RESPONDING:\n return new ServiceNotRespondingError(\n errorResponse as unknown as ErrorResponse<PortErrorContext>\n );\n\n case ErrorCode.PORT_IN_USE:\n return new PortInUseError(\n errorResponse as unknown as ErrorResponse<PortErrorContext>\n );\n\n case ErrorCode.PORT_OPERATION_ERROR:\n return new PortError(\n errorResponse as unknown as ErrorResponse<PortErrorContext>\n );\n\n case ErrorCode.CUSTOM_DOMAIN_REQUIRED:\n return new CustomDomainRequiredError(\n errorResponse as unknown as ErrorResponse<InternalErrorContext>\n );\n\n // Git Errors\n case ErrorCode.GIT_REPOSITORY_NOT_FOUND:\n return new GitRepositoryNotFoundError(\n errorResponse as unknown as ErrorResponse<GitRepositoryNotFoundContext>\n );\n\n case ErrorCode.GIT_AUTH_FAILED:\n return new GitAuthenticationError(\n errorResponse as unknown as ErrorResponse<GitAuthFailedContext>\n );\n\n case ErrorCode.GIT_BRANCH_NOT_FOUND:\n return new GitBranchNotFoundError(\n errorResponse as unknown as ErrorResponse<GitBranchNotFoundContext>\n );\n\n case ErrorCode.GIT_NETWORK_ERROR:\n return new GitNetworkError(\n errorResponse as unknown as ErrorResponse<GitErrorContext>\n );\n\n case ErrorCode.GIT_CLONE_FAILED:\n return new GitCloneError(\n errorResponse as unknown as ErrorResponse<GitErrorContext>\n );\n\n case ErrorCode.GIT_CHECKOUT_FAILED:\n return new GitCheckoutError(\n errorResponse as unknown as ErrorResponse<GitErrorContext>\n );\n\n case ErrorCode.INVALID_GIT_URL:\n return new InvalidGitUrlError(\n errorResponse as unknown as ErrorResponse<ValidationFailedContext>\n );\n\n case ErrorCode.GIT_OPERATION_FAILED:\n return new GitError(\n errorResponse as unknown as ErrorResponse<GitErrorContext>\n );\n\n // Code Interpreter Errors\n case ErrorCode.INTERPRETER_NOT_READY:\n return new InterpreterNotReadyError(\n errorResponse as unknown as ErrorResponse<InterpreterNotReadyContext>\n );\n\n case ErrorCode.CONTEXT_NOT_FOUND:\n return new ContextNotFoundError(\n errorResponse as unknown as ErrorResponse<ContextNotFoundContext>\n );\n\n case ErrorCode.CODE_EXECUTION_ERROR:\n return new CodeExecutionError(\n errorResponse as unknown as ErrorResponse<CodeExecutionContext>\n );\n\n // Validation Errors\n case ErrorCode.VALIDATION_FAILED:\n return new ValidationFailedError(\n errorResponse as unknown as ErrorResponse<ValidationFailedContext>\n );\n\n // Generic Errors\n case ErrorCode.INVALID_JSON_RESPONSE:\n case ErrorCode.UNKNOWN_ERROR:\n case ErrorCode.INTERNAL_ERROR:\n return new SandboxError(\n errorResponse as unknown as ErrorResponse<InternalErrorContext>\n );\n\n default:\n // Fallback for unknown error codes\n return new SandboxError(errorResponse);\n }\n}\n","import type { Logger } from '@repo/shared';\nimport { createNoOpLogger } from '@repo/shared';\nimport { getHttpStatus } from '@repo/shared/errors';\nimport type { ErrorResponse as NewErrorResponse } from '../errors';\nimport { createErrorFromResponse, ErrorCode } from '../errors';\nimport type { SandboxError } from '../errors/classes';\nimport type { HttpClientOptions, ResponseHandler } from './types';\n\n// Container startup retry configuration\nconst TIMEOUT_MS = 120_000; // 2 minutes total retry budget\nconst MIN_TIME_FOR_RETRY_MS = 15_000; // Need at least 15s remaining to retry (allows for longer container startups)\n\n/**\n * Abstract base class providing common HTTP functionality for all domain clients\n */\nexport abstract class BaseHttpClient {\n protected baseUrl: string;\n protected options: HttpClientOptions;\n protected logger: Logger;\n\n constructor(options: HttpClientOptions = {}) {\n this.options = options;\n this.logger = options.logger ?? createNoOpLogger();\n this.baseUrl = this.options.baseUrl!;\n }\n\n /**\n * Core HTTP request method with automatic retry for container startup delays\n * Retries both 503 (provisioning) and 500 (startup failure) errors when they're container-related\n */\n protected async doFetch(\n path: string,\n options?: RequestInit\n ): Promise<Response> {\n const startTime = Date.now();\n let attempt = 0;\n\n while (true) {\n const response = await this.executeFetch(path, options);\n\n // Check if this is a retryable container error (both 500 and 503)\n const shouldRetry = await this.isRetryableContainerError(response);\n\n if (shouldRetry) {\n const elapsed = Date.now() - startTime;\n const remaining = TIMEOUT_MS - elapsed;\n\n // Check if we have enough time for another attempt\n if (remaining > MIN_TIME_FOR_RETRY_MS) {\n // Exponential backoff with longer delays for container ops: 3s, 6s, 12s, 24s, 30s\n const delay = Math.min(3000 * 2 ** attempt, 30000);\n\n this.logger.info('Container not ready, retrying', {\n status: response.status,\n attempt: attempt + 1,\n delayMs: delay,\n remainingSec: Math.floor(remaining / 1000)\n });\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n attempt++;\n continue;\n }\n\n // Timeout exhausted\n this.logger.error(\n 'Container failed to become ready',\n new Error(\n `Failed after ${attempt + 1} attempts over ${Math.floor(elapsed / 1000)}s`\n )\n );\n return response;\n }\n\n // Not a retryable error or request succeeded\n return response;\n }\n }\n\n /**\n * Make a POST request with JSON body\n */\n protected async post<T>(\n endpoint: string,\n data: unknown,\n responseHandler?: ResponseHandler<T>\n ): Promise<T> {\n const response = await this.doFetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n });\n\n return this.handleResponse(response, responseHandler);\n }\n\n /**\n * Make a GET request\n */\n protected async get<T>(\n endpoint: string,\n responseHandler?: ResponseHandler<T>\n ): Promise<T> {\n const response = await this.doFetch(endpoint, {\n method: 'GET'\n });\n\n return this.handleResponse(response, responseHandler);\n }\n\n /**\n * Make a DELETE request\n */\n protected async delete<T>(\n endpoint: string,\n responseHandler?: ResponseHandler<T>\n ): Promise<T> {\n const response = await this.doFetch(endpoint, {\n method: 'DELETE'\n });\n\n return this.handleResponse(response, responseHandler);\n }\n\n /**\n * Handle HTTP response with error checking and parsing\n */\n protected async handleResponse<T>(\n response: Response,\n customHandler?: ResponseHandler<T>\n ): Promise<T> {\n if (!response.ok) {\n await this.handleErrorResponse(response);\n }\n\n if (customHandler) {\n return customHandler(response);\n }\n\n try {\n return await response.json();\n } catch (error) {\n // Handle malformed JSON responses gracefully\n const errorResponse: NewErrorResponse = {\n code: ErrorCode.INVALID_JSON_RESPONSE,\n message: `Invalid JSON response: ${\n error instanceof Error ? error.message : 'Unknown parsing error'\n }`,\n context: {},\n httpStatus: response.status,\n timestamp: new Date().toISOString()\n };\n throw createErrorFromResponse(errorResponse);\n }\n }\n\n /**\n * Handle error responses with consistent error throwing\n */\n protected async handleErrorResponse(response: Response): Promise<never> {\n let errorData: NewErrorResponse;\n\n try {\n errorData = await response.json();\n } catch {\n // Fallback if response isn't JSON or parsing fails\n errorData = {\n code: ErrorCode.INTERNAL_ERROR,\n message: `HTTP error! status: ${response.status}`,\n context: { statusText: response.statusText },\n httpStatus: response.status,\n timestamp: new Date().toISOString()\n };\n }\n\n // Convert ErrorResponse to appropriate Error class\n const error = createErrorFromResponse(errorData);\n\n // Call error callback if provided\n this.options.onError?.(errorData.message, undefined);\n\n throw error;\n }\n\n /**\n * Create a streaming response handler for Server-Sent Events\n */\n protected async handleStreamResponse(\n response: Response\n ): Promise<ReadableStream<Uint8Array>> {\n if (!response.ok) {\n await this.handleErrorResponse(response);\n }\n\n if (!response.body) {\n throw new Error('No response body for streaming');\n }\n\n return response.body;\n }\n\n /**\n * Utility method to log successful operations\n */\n protected logSuccess(operation: string, details?: string): void {\n this.logger.info(\n `${operation} completed successfully`,\n details ? { details } : undefined\n );\n }\n\n /**\n * Utility method to log errors intelligently\n * Only logs unexpected errors (5xx), not expected errors (4xx)\n *\n * - 4xx errors (validation, not found, conflicts): Don't log (expected client errors)\n * - 5xx errors (server failures, internal errors): DO log (unexpected server errors)\n */\n protected logError(operation: string, error: unknown): void {\n // Check if it's a SandboxError with HTTP status\n if (error && typeof error === 'object' && 'httpStatus' in error) {\n const httpStatus = (error as SandboxError).httpStatus;\n\n // Only log server errors (5xx), not client errors (4xx)\n if (httpStatus >= 500) {\n this.logger.error(\n `Unexpected error in ${operation}`,\n error instanceof Error ? error : new Error(String(error)),\n { httpStatus }\n );\n }\n // 4xx errors are expected (validation, not found, etc.) - don't log\n } else {\n // Non-SandboxError (unexpected) - log it\n this.logger.error(\n `Error in ${operation}`,\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n\n /**\n * Check if response indicates a retryable container error\n * Uses fail-safe strategy: only retry known transient errors\n *\n * TODO: This relies on string matching error messages, which is brittle.\n * Ideally, the container API should return structured errors with a\n * `retryable: boolean` field to avoid coupling to error message format.\n *\n * @param response - HTTP response to check\n * @returns true if error is retryable container error, false otherwise\n */\n private async isRetryableContainerError(\n response: Response\n ): Promise<boolean> {\n // Only consider 500 and 503 status codes\n if (response.status !== 500 && response.status !== 503) {\n return false;\n }\n\n try {\n const cloned = response.clone();\n const text = await cloned.text();\n const textLower = text.toLowerCase();\n\n // Step 1: Check for permanent errors (fail fast)\n const permanentErrors = [\n 'no such image', // Missing Docker image\n 'container already exists', // Name collision\n 'malformed containerinspect' // Docker API issue\n ];\n\n if (permanentErrors.some((err) => textLower.includes(err))) {\n this.logger.debug('Detected permanent error, not retrying', { text });\n return false; // Don't retry\n }\n\n // Step 2: Check for known transient errors (do retry)\n const transientErrors = [\n // Platform provisioning (503)\n 'no container instance available',\n 'currently provisioning',\n\n // Port mapping race conditions (500)\n 'container port not found',\n 'connection refused: container port',\n\n // Application startup delays (500)\n 'the container is not listening',\n 'failed to verify port',\n 'container did not start',\n\n // Network transients (500)\n 'network connection lost',\n 'container suddenly disconnected',\n\n // Monitor race conditions (500)\n 'monitor failed to find container',\n\n // General timeouts (500)\n 'timed out',\n 'timeout'\n ];\n\n const shouldRetry = transientErrors.some((err) =>\n textLower.includes(err)\n );\n\n if (!shouldRetry) {\n this.logger.debug('Unknown error pattern, not retrying', {\n status: response.status,\n text: text.substring(0, 200) // Log first 200 chars\n });\n }\n\n return shouldRetry;\n } catch (error) {\n this.logger.error(\n 'Error checking if response is retryable',\n error instanceof Error ? error : new Error(String(error))\n );\n // If we can't read response, don't retry (fail fast)\n return false;\n }\n }\n\n private async executeFetch(\n path: string,\n options?: RequestInit\n ): Promise<Response> {\n const url = this.options.stub\n ? `http://localhost:${this.options.port}${path}`\n : `${this.baseUrl}${path}`;\n\n try {\n if (this.options.stub) {\n return await this.options.stub.containerFetch(\n url,\n options || {},\n this.options.port\n );\n } else {\n return await fetch(url, options);\n }\n } catch (error) {\n this.logger.error(\n 'HTTP request error',\n error instanceof Error ? error : new Error(String(error)),\n { method: options?.method || 'GET', url }\n );\n throw error;\n }\n }\n}\n","import type { ExecuteRequest } from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { BaseApiResponse } from './types';\n\n/**\n * Request interface for command execution\n */\nexport type { ExecuteRequest };\n\n/**\n * Response interface for command execution\n */\nexport interface ExecuteResponse extends BaseApiResponse {\n stdout: string;\n stderr: string;\n exitCode: number;\n command: string;\n}\n\n/**\n * Client for command execution operations\n */\nexport class CommandClient extends BaseHttpClient {\n /**\n * Execute a command and return the complete result\n * @param command - The command to execute\n * @param sessionId - The session ID for this command execution\n * @param timeoutMs - Optional timeout in milliseconds (unlimited by default)\n * @param env - Optional environment variables for this command\n * @param cwd - Optional working directory for this command\n */\n async execute(\n command: string,\n sessionId: string,\n options?: {\n timeoutMs?: number;\n env?: Record<string, string>;\n cwd?: string;\n }\n ): Promise<ExecuteResponse> {\n try {\n const data: ExecuteRequest = {\n command,\n sessionId,\n ...(options?.timeoutMs !== undefined && {\n timeoutMs: options.timeoutMs\n }),\n ...(options?.env !== undefined && { env: options.env }),\n ...(options?.cwd !== undefined && { cwd: options.cwd })\n };\n\n const response = await this.post<ExecuteResponse>('/api/execute', data);\n\n this.logSuccess(\n 'Command executed',\n `${command}, Success: ${response.success}`\n );\n\n // Call the callback if provided\n this.options.onCommandComplete?.(\n response.success,\n response.exitCode,\n response.stdout,\n response.stderr,\n response.command\n );\n\n return response;\n } catch (error) {\n this.logError('execute', error);\n\n // Call error callback if provided\n this.options.onError?.(\n error instanceof Error ? error.message : String(error),\n command\n );\n\n throw error;\n }\n }\n\n /**\n * Execute a command and return a stream of events\n * @param command - The command to execute\n * @param sessionId - The session ID for this command execution\n * @param options - Optional per-command execution settings\n */\n async executeStream(\n command: string,\n sessionId: string,\n options?: {\n timeoutMs?: number;\n env?: Record<string, string>;\n cwd?: string;\n }\n ): Promise<ReadableStream<Uint8Array>> {\n try {\n const data = {\n command,\n sessionId,\n ...(options?.timeoutMs !== undefined && {\n timeoutMs: options.timeoutMs\n }),\n ...(options?.env !== undefined && { env: options.env }),\n ...(options?.cwd !== undefined && { cwd: options.cwd })\n };\n\n const response = await this.doFetch('/api/execute/stream', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n });\n\n const stream = await this.handleStreamResponse(response);\n\n this.logSuccess('Command stream started', command);\n\n return stream;\n } catch (error) {\n this.logError('executeStream', error);\n\n // Call error callback if provided\n this.options.onError?.(\n error instanceof Error ? error.message : String(error),\n command\n );\n\n throw error;\n }\n }\n}\n","import type {\n DeleteFileResult,\n FileExistsResult,\n ListFilesOptions,\n ListFilesResult,\n MkdirResult,\n MoveFileResult,\n ReadFileResult,\n RenameFileResult,\n WriteFileResult\n} from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { HttpClientOptions, SessionRequest } from './types';\n\n/**\n * Request interface for creating directories\n */\nexport interface MkdirRequest extends SessionRequest {\n path: string;\n recursive?: boolean;\n}\n\n/**\n * Request interface for writing files\n */\nexport interface WriteFileRequest extends SessionRequest {\n path: string;\n content: string;\n encoding?: string;\n}\n\n/**\n * Request interface for reading files\n */\nexport interface ReadFileRequest extends SessionRequest {\n path: string;\n encoding?: string;\n}\n\n/**\n * Request interface for file operations (delete, rename, move)\n */\nexport interface FileOperationRequest extends SessionRequest {\n path: string;\n newPath?: string; // For rename/move operations\n}\n\n/**\n * Client for file system operations\n */\nexport class FileClient extends BaseHttpClient {\n /**\n * Create a directory\n * @param path - Directory path to create\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (recursive)\n */\n async mkdir(\n path: string,\n sessionId: string,\n options?: { recursive?: boolean }\n ): Promise<MkdirResult> {\n try {\n const data = {\n path,\n sessionId,\n recursive: options?.recursive ?? false\n };\n\n const response = await this.post<MkdirResult>('/api/mkdir', data);\n\n this.logSuccess(\n 'Directory created',\n `${path} (recursive: ${data.recursive})`\n );\n return response;\n } catch (error) {\n this.logError('mkdir', error);\n throw error;\n }\n }\n\n /**\n * Write content to a file\n * @param path - File path to write to\n * @param content - Content to write\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (encoding)\n */\n async writeFile(\n path: string,\n content: string,\n sessionId: string,\n options?: { encoding?: string }\n ): Promise<WriteFileResult> {\n try {\n const data = {\n path,\n content,\n sessionId,\n encoding: options?.encoding\n };\n\n const response = await this.post<WriteFileResult>('/api/write', data);\n\n this.logSuccess('File written', `${path} (${content.length} chars)`);\n return response;\n } catch (error) {\n this.logError('writeFile', error);\n throw error;\n }\n }\n\n /**\n * Read content from a file\n * @param path - File path to read from\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (encoding)\n */\n async readFile(\n path: string,\n sessionId: string,\n options?: { encoding?: string }\n ): Promise<ReadFileResult> {\n try {\n const data = {\n path,\n sessionId,\n encoding: options?.encoding\n };\n\n const response = await this.post<ReadFileResult>('/api/read', data);\n\n this.logSuccess(\n 'File read',\n `${path} (${response.content.length} chars)`\n );\n return response;\n } catch (error) {\n this.logError('readFile', error);\n throw error;\n }\n }\n\n /**\n * Stream a file using Server-Sent Events\n * Returns a ReadableStream of SSE events containing metadata, chunks, and completion\n * @param path - File path to stream\n * @param sessionId - The session ID for this operation\n */\n async readFileStream(\n path: string,\n sessionId: string\n ): Promise<ReadableStream<Uint8Array>> {\n try {\n const data = {\n path,\n sessionId\n };\n\n const response = await this.doFetch('/api/read/stream', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n });\n\n const stream = await this.handleStreamResponse(response);\n this.logSuccess('File stream started', path);\n return stream;\n } catch (error) {\n this.logError('readFileStream', error);\n throw error;\n }\n }\n\n /**\n * Delete a file\n * @param path - File path to delete\n * @param sessionId - The session ID for this operation\n */\n async deleteFile(path: string, sessionId: string): Promise<DeleteFileResult> {\n try {\n const data = { path, sessionId };\n\n const response = await this.post<DeleteFileResult>('/api/delete', data);\n\n this.logSuccess('File deleted', path);\n return response;\n } catch (error) {\n this.logError('deleteFile', error);\n throw error;\n }\n }\n\n /**\n * Rename a file\n * @param path - Current file path\n * @param newPath - New file path\n * @param sessionId - The session ID for this operation\n */\n async renameFile(\n path: string,\n newPath: string,\n sessionId: string\n ): Promise<RenameFileResult> {\n try {\n const data = { oldPath: path, newPath, sessionId };\n\n const response = await this.post<RenameFileResult>('/api/rename', data);\n\n this.logSuccess('File renamed', `${path} -> ${newPath}`);\n return response;\n } catch (error) {\n this.logError('renameFile', error);\n throw error;\n }\n }\n\n /**\n * Move a file\n * @param path - Current file path\n * @param newPath - Destination file path\n * @param sessionId - The session ID for this operation\n */\n async moveFile(\n path: string,\n newPath: string,\n sessionId: string\n ): Promise<MoveFileResult> {\n try {\n const data = { sourcePath: path, destinationPath: newPath, sessionId };\n\n const response = await this.post<MoveFileResult>('/api/move', data);\n\n this.logSuccess('File moved', `${path} -> ${newPath}`);\n return response;\n } catch (error) {\n this.logError('moveFile', error);\n throw error;\n }\n }\n\n /**\n * List files in a directory\n * @param path - Directory path to list\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (recursive, includeHidden)\n */\n async listFiles(\n path: string,\n sessionId: string,\n options?: ListFilesOptions\n ): Promise<ListFilesResult> {\n try {\n const data = {\n path,\n sessionId,\n options: options || {}\n };\n\n const response = await this.post<ListFilesResult>(\n '/api/list-files',\n data\n );\n\n this.logSuccess('Files listed', `${path} (${response.count} files)`);\n return response;\n } catch (error) {\n this.logError('listFiles', error);\n throw error;\n }\n }\n\n /**\n * Check if a file or directory exists\n * @param path - Path to check\n * @param sessionId - The session ID for this operation\n */\n async exists(path: string, sessionId: string): Promise<FileExistsResult> {\n try {\n const data = {\n path,\n sessionId\n };\n\n const response = await this.post<FileExistsResult>('/api/exists', data);\n\n this.logSuccess(\n 'Path existence checked',\n `${path} (exists: ${response.exists})`\n );\n return response;\n } catch (error) {\n this.logError('exists', error);\n throw error;\n }\n }\n}\n","import type { GitCheckoutResult } from '@repo/shared';\nimport { GitLogger } from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { HttpClientOptions, SessionRequest } from './types';\n\n// Re-export for convenience\nexport type { GitCheckoutResult };\n\n/**\n * Request interface for Git checkout operations\n */\nexport interface GitCheckoutRequest extends SessionRequest {\n repoUrl: string;\n branch?: string;\n targetDir?: string;\n}\n\n/**\n * Client for Git repository operations\n */\nexport class GitClient extends BaseHttpClient {\n constructor(options: HttpClientOptions = {}) {\n super(options);\n // Wrap logger with GitLogger to auto-redact credentials\n this.logger = new GitLogger(this.logger);\n }\n\n /**\n * Clone a Git repository\n * @param repoUrl - URL of the Git repository to clone\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (branch, targetDir)\n */\n async checkout(\n repoUrl: string,\n sessionId: string,\n options?: {\n branch?: string;\n targetDir?: string;\n }\n ): Promise<GitCheckoutResult> {\n try {\n // Determine target directory - use provided path or generate from repo name\n let targetDir = options?.targetDir;\n if (!targetDir) {\n const repoName = this.extractRepoName(repoUrl);\n // Ensure absolute path in /workspace\n targetDir = `/workspace/${repoName}`;\n }\n\n const data: GitCheckoutRequest = {\n repoUrl,\n sessionId,\n targetDir\n };\n\n // Only include branch if explicitly specified\n // This allows Git to use the repository's default branch\n if (options?.branch) {\n data.branch = options.branch;\n }\n\n const response = await this.post<GitCheckoutResult>(\n '/api/git/checkout',\n data\n );\n\n this.logSuccess(\n 'Repository cloned',\n `${repoUrl} (branch: ${response.branch}) -> ${response.targetDir}`\n );\n\n return response;\n } catch (error) {\n this.logError('checkout', error);\n throw error;\n }\n }\n\n /**\n * Extract repository name from URL for default directory name\n */\n private extractRepoName(repoUrl: string): string {\n try {\n const url = new URL(repoUrl);\n const pathParts = url.pathname.split('/');\n const repoName = pathParts[pathParts.length - 1];\n\n // Remove .git extension if present\n return repoName.replace(/\\.git$/, '');\n } catch {\n // Fallback for invalid URLs\n const parts = repoUrl.split('/');\n const repoName = parts[parts.length - 1];\n return repoName.replace(/\\.git$/, '') || 'repo';\n }\n }\n}\n","import {\n type CodeContext,\n type ContextCreateResult,\n type ContextListResult,\n type CreateContextOptions,\n type ExecutionError,\n type OutputMessage,\n type Result,\n ResultImpl\n} from '@repo/shared';\nimport type { ErrorResponse } from '../errors';\nimport {\n createErrorFromResponse,\n ErrorCode,\n InterpreterNotReadyError\n} from '../errors';\nimport { BaseHttpClient } from './base-client.js';\nimport type { HttpClientOptions } from './types.js';\n\n// Streaming execution data from the server\ninterface StreamingExecutionData {\n type: 'result' | 'stdout' | 'stderr' | 'error' | 'execution_complete';\n text?: string;\n html?: string;\n png?: string; // base64\n jpeg?: string; // base64\n svg?: string;\n latex?: string;\n markdown?: string;\n javascript?: string;\n json?: unknown;\n chart?: {\n type:\n | 'line'\n | 'bar'\n | 'scatter'\n | 'pie'\n | 'histogram'\n | 'heatmap'\n | 'unknown';\n data: unknown;\n options?: unknown;\n };\n data?: unknown;\n metadata?: Record<string, unknown>;\n execution_count?: number;\n ename?: string;\n evalue?: string;\n traceback?: string[];\n lineNumber?: number;\n timestamp?: number;\n}\n\nexport interface ExecutionCallbacks {\n onStdout?: (output: OutputMessage) => void | Promise<void>;\n onStderr?: (output: OutputMessage) => void | Promise<void>;\n onResult?: (result: Result) => void | Promise<void>;\n onError?: (error: ExecutionError) => void | Promise<void>;\n}\n\nexport class InterpreterClient extends BaseHttpClient {\n private readonly maxRetries = 3;\n private readonly retryDelayMs = 1000;\n\n async createCodeContext(\n options: CreateContextOptions = {}\n ): Promise<CodeContext> {\n return this.executeWithRetry(async () => {\n const response = await this.doFetch('/api/contexts', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n language: options.language || 'python',\n cwd: options.cwd || '/workspace',\n env_vars: options.envVars\n })\n });\n\n if (!response.ok) {\n const error = await this.parseErrorResponse(response);\n throw error;\n }\n\n const data = (await response.json()) as ContextCreateResult;\n if (!data.success) {\n throw new Error(`Failed to create context: ${JSON.stringify(data)}`);\n }\n\n return {\n id: data.contextId,\n language: data.language,\n cwd: data.cwd || '/workspace',\n createdAt: new Date(data.timestamp),\n lastUsed: new Date(data.timestamp)\n };\n });\n }\n\n async runCodeStream(\n contextId: string | undefined,\n code: string,\n language: string | undefined,\n callbacks: ExecutionCallbacks,\n timeoutMs?: number\n ): Promise<void> {\n return this.executeWithRetry(async () => {\n const response = await this.doFetch('/api/execute/code', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream'\n },\n body: JSON.stringify({\n context_id: contextId,\n code,\n language,\n ...(timeoutMs !== undefined && { timeout_ms: timeoutMs })\n })\n });\n\n if (!response.ok) {\n const error = await this.parseErrorResponse(response);\n throw error;\n }\n\n if (!response.body) {\n throw new Error('No response body for streaming execution');\n }\n\n // Process streaming response\n for await (const chunk of this.readLines(response.body)) {\n await this.parseExecutionResult(chunk, callbacks);\n }\n });\n }\n\n async listCodeContexts(): Promise<CodeContext[]> {\n return this.executeWithRetry(async () => {\n const response = await this.doFetch('/api/contexts', {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' }\n });\n\n if (!response.ok) {\n const error = await this.parseErrorResponse(response);\n throw error;\n }\n\n const data = (await response.json()) as ContextListResult;\n if (!data.success) {\n throw new Error(`Failed to list contexts: ${JSON.stringify(data)}`);\n }\n\n return data.contexts.map((ctx) => ({\n id: ctx.id,\n language: ctx.language,\n cwd: ctx.cwd || '/workspace',\n createdAt: new Date(data.timestamp),\n lastUsed: new Date(data.timestamp)\n }));\n });\n }\n\n async deleteCodeContext(contextId: string): Promise<void> {\n return this.executeWithRetry(async () => {\n const response = await this.doFetch(`/api/contexts/${contextId}`, {\n method: 'DELETE',\n headers: { 'Content-Type': 'application/json' }\n });\n\n if (!response.ok) {\n const error = await this.parseErrorResponse(response);\n throw error;\n }\n });\n }\n\n /**\n * Execute an operation with automatic retry for transient errors\n */\n private async executeWithRetry<T>(operation: () => Promise<T>): Promise<T> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt < this.maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n this.logError('executeWithRetry', error);\n lastError = error as Error;\n\n // Check if it's a retryable error (interpreter not ready)\n if (this.isRetryableError(error)) {\n // Don't retry on the last attempt\n if (attempt < this.maxRetries - 1) {\n // Exponential backoff with jitter\n const delay =\n this.retryDelayMs * 2 ** attempt + Math.random() * 1000;\n await new Promise((resolve) => setTimeout(resolve, delay));\n continue;\n }\n }\n\n // Not retryable or last attempt - throw the error\n throw error;\n }\n }\n\n throw lastError || new Error('Execution failed after retries');\n }\n\n private isRetryableError(error: unknown): boolean {\n if (error instanceof InterpreterNotReadyError) {\n return true;\n }\n\n if (error instanceof Error) {\n return (\n error.message.includes('not ready') ||\n error.message.includes('initializing')\n );\n }\n\n return false;\n }\n\n private async parseErrorResponse(response: Response): Promise<Error> {\n try {\n const errorData = (await response.json()) as ErrorResponse;\n return createErrorFromResponse(errorData);\n } catch {\n // Fallback if response isn't JSON\n const errorResponse: ErrorResponse = {\n code: ErrorCode.INTERNAL_ERROR,\n message: `HTTP ${response.status}: ${response.statusText}`,\n context: {},\n httpStatus: response.status,\n timestamp: new Date().toISOString()\n };\n return createErrorFromResponse(errorResponse);\n }\n }\n\n private async *readLines(\n stream: ReadableStream<Uint8Array>\n ): AsyncGenerator<string> {\n const reader = stream.getReader();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (value) {\n buffer += new TextDecoder().decode(value);\n }\n if (done) break;\n\n let newlineIdx = buffer.indexOf('\\n');\n while (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx);\n buffer = buffer.slice(newlineIdx + 1);\n newlineIdx = buffer.indexOf('\\n');\n }\n }\n\n // Yield any remaining data\n if (buffer.length > 0) {\n yield buffer;\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n private async parseExecutionResult(\n line: string,\n callbacks: ExecutionCallbacks\n ) {\n if (!line.trim()) return;\n\n // Skip lines that don't start with \"data: \" (SSE format)\n if (!line.startsWith('data: ')) return;\n\n try {\n // Strip \"data: \" prefix and parse JSON\n const jsonData = line.substring(6); // \"data: \" is 6 characters\n const data = JSON.parse(jsonData) as StreamingExecutionData;\n\n switch (data.type) {\n case 'stdout':\n if (callbacks.onStdout && data.text) {\n await callbacks.onStdout({\n text: data.text,\n timestamp: data.timestamp || Date.now()\n });\n }\n break;\n\n case 'stderr':\n if (callbacks.onStderr && data.text) {\n await callbacks.onStderr({\n text: data.text,\n timestamp: data.timestamp || Date.now()\n });\n }\n break;\n\n case 'result':\n if (callbacks.onResult) {\n // Create a ResultImpl instance from the raw data\n const result = new ResultImpl(data);\n await callbacks.onResult(result);\n }\n break;\n\n case 'error':\n if (callbacks.onError) {\n await callbacks.onError({\n name: data.ename || 'Error',\n message: data.evalue || 'Unknown error',\n traceback: data.traceback || []\n });\n }\n break;\n\n case 'execution_complete':\n // Signal completion - callbacks can handle cleanup if needed\n break;\n }\n } catch (error) {\n this.logError('parseExecutionResult', error);\n }\n }\n}\n","import type {\n PortCloseResult,\n PortExposeResult,\n PortListResult\n} from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { HttpClientOptions } from './types';\n\n// Re-export for convenience\nexport type { PortExposeResult, PortCloseResult, PortListResult };\n\n/**\n * Request interface for exposing ports\n */\nexport interface ExposePortRequest {\n port: number;\n name?: string;\n}\n\n/**\n * Request interface for unexposing ports\n */\nexport interface UnexposePortRequest {\n port: number;\n}\n\n/**\n * Client for port management and preview URL operations\n */\nexport class PortClient extends BaseHttpClient {\n /**\n * Expose a port and get a preview URL\n * @param port - Port number to expose\n * @param sessionId - The session ID for this operation\n * @param name - Optional name for the port\n */\n async exposePort(\n port: number,\n sessionId: string,\n name?: string\n ): Promise<PortExposeResult> {\n try {\n const data = { port, sessionId, name };\n\n const response = await this.post<PortExposeResult>(\n '/api/expose-port',\n data\n );\n\n this.logSuccess(\n 'Port exposed',\n `${port} exposed at ${response.url}${name ? ` (${name})` : ''}`\n );\n\n return response;\n } catch (error) {\n this.logError('exposePort', error);\n throw error;\n }\n }\n\n /**\n * Unexpose a port and remove its preview URL\n * @param port - Port number to unexpose\n * @param sessionId - The session ID for this operation\n */\n async unexposePort(\n port: number,\n sessionId: string\n ): Promise<PortCloseResult> {\n try {\n const url = `/api/exposed-ports/${port}?session=${encodeURIComponent(\n sessionId\n )}`;\n const response = await this.delete<PortCloseResult>(url);\n\n this.logSuccess('Port unexposed', `${port}`);\n return response;\n } catch (error) {\n this.logError('unexposePort', error);\n throw error;\n }\n }\n\n /**\n * Get all currently exposed ports\n * @param sessionId - The session ID for this operation\n */\n async getExposedPorts(sessionId: string): Promise<PortListResult> {\n try {\n const url = `/api/exposed-ports?session=${encodeURIComponent(sessionId)}`;\n const response = await this.get<PortListResult>(url);\n\n this.logSuccess(\n 'Exposed ports retrieved',\n `${response.ports.length} ports exposed`\n );\n\n return response;\n } catch (error) {\n this.logError('getExposedPorts', error);\n throw error;\n }\n }\n}\n","import type {\n ProcessCleanupResult,\n ProcessInfoResult,\n ProcessKillResult,\n ProcessListResult,\n ProcessLogsResult,\n ProcessStartResult,\n StartProcessRequest\n} from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { HttpClientOptions } from './types';\n\n// Re-export for convenience\nexport type {\n StartProcessRequest,\n ProcessStartResult,\n ProcessListResult,\n ProcessInfoResult,\n ProcessKillResult,\n ProcessLogsResult,\n ProcessCleanupResult\n};\n\n/**\n * Client for background process management\n */\nexport class ProcessClient extends BaseHttpClient {\n /**\n * Start a background process\n * @param command - Command to execute as a background process\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (processId)\n */\n async startProcess(\n command: string,\n sessionId: string,\n options?: {\n processId?: string;\n timeoutMs?: number;\n env?: Record<string, string>;\n cwd?: string;\n encoding?: string;\n autoCleanup?: boolean;\n }\n ): Promise<ProcessStartResult> {\n try {\n const data: StartProcessRequest = {\n command,\n sessionId,\n ...(options?.processId !== undefined && {\n processId: options.processId\n }),\n ...(options?.timeoutMs !== undefined && {\n timeoutMs: options.timeoutMs\n }),\n ...(options?.env !== undefined && { env: options.env }),\n ...(options?.cwd !== undefined && { cwd: options.cwd }),\n ...(options?.encoding !== undefined && { encoding: options.encoding }),\n ...(options?.autoCleanup !== undefined && {\n autoCleanup: options.autoCleanup\n })\n };\n\n const response = await this.post<ProcessStartResult>(\n '/api/process/start',\n data\n );\n\n this.logSuccess(\n 'Process started',\n `${command} (ID: ${response.processId})`\n );\n\n return response;\n } catch (error) {\n this.logError('startProcess', error);\n throw error;\n }\n }\n\n /**\n * List all processes (sandbox-scoped, not session-scoped)\n */\n async listProcesses(): Promise<ProcessListResult> {\n try {\n const url = `/api/process/list`;\n const response = await this.get<ProcessListResult>(url);\n\n this.logSuccess(\n 'Processes listed',\n `${response.processes.length} processes`\n );\n return response;\n } catch (error) {\n this.logError('listProcesses', error);\n throw error;\n }\n }\n\n /**\n * Get information about a specific process (sandbox-scoped, not session-scoped)\n * @param processId - ID of the process to retrieve\n */\n async getProcess(processId: string): Promise<ProcessInfoResult> {\n try {\n const url = `/api/process/${processId}`;\n const response = await this.get<ProcessInfoResult>(url);\n\n this.logSuccess('Process retrieved', `ID: ${processId}`);\n return response;\n } catch (error) {\n this.logError('getProcess', error);\n throw error;\n }\n }\n\n /**\n * Kill a specific process (sandbox-scoped, not session-scoped)\n * @param processId - ID of the process to kill\n */\n async killProcess(processId: string): Promise<ProcessKillResult> {\n try {\n const url = `/api/process/${processId}`;\n const response = await this.delete<ProcessKillResult>(url);\n\n this.logSuccess('Process killed', `ID: ${processId}`);\n return response;\n } catch (error) {\n this.logError('killProcess', error);\n throw error;\n }\n }\n\n /**\n * Kill all running processes (sandbox-scoped, not session-scoped)\n */\n async killAllProcesses(): Promise<ProcessCleanupResult> {\n try {\n const url = `/api/process/kill-all`;\n const response = await this.delete<ProcessCleanupResult>(url);\n\n this.logSuccess(\n 'All processes killed',\n `${response.cleanedCount} processes terminated`\n );\n\n return response;\n } catch (error) {\n this.logError('killAllProcesses', error);\n throw error;\n }\n }\n\n /**\n * Get logs from a specific process (sandbox-scoped, not session-scoped)\n * @param processId - ID of the process to get logs from\n */\n async getProcessLogs(processId: string): Promise<ProcessLogsResult> {\n try {\n const url = `/api/process/${processId}/logs`;\n const response = await this.get<ProcessLogsResult>(url);\n\n this.logSuccess(\n 'Process logs retrieved',\n `ID: ${processId}, stdout: ${response.stdout.length} chars, stderr: ${response.stderr.length} chars`\n );\n\n return response;\n } catch (error) {\n this.logError('getProcessLogs', error);\n throw error;\n }\n }\n\n /**\n * Stream logs from a specific process (sandbox-scoped, not session-scoped)\n * @param processId - ID of the process to stream logs from\n */\n async streamProcessLogs(\n processId: string\n ): Promise<ReadableStream<Uint8Array>> {\n try {\n const url = `/api/process/${processId}/stream`;\n const response = await this.doFetch(url, {\n method: 'GET'\n });\n\n const stream = await this.handleStreamResponse(response);\n\n this.logSuccess('Process log stream started', `ID: ${processId}`);\n\n return stream;\n } catch (error) {\n this.logError('streamProcessLogs', error);\n throw error;\n }\n }\n}\n","import { BaseHttpClient } from './base-client';\nimport type { BaseApiResponse, HttpClientOptions } from './types';\n\n/**\n * Response interface for ping operations\n */\nexport interface PingResponse extends BaseApiResponse {\n message: string;\n uptime?: number;\n}\n\n/**\n * Response interface for getting available commands\n */\nexport interface CommandsResponse extends BaseApiResponse {\n availableCommands: string[];\n count: number;\n}\n\n/**\n * Response interface for getting container version\n */\nexport interface VersionResponse extends BaseApiResponse {\n version: string;\n}\n\n/**\n * Request interface for creating sessions\n */\nexport interface CreateSessionRequest {\n id: string;\n env?: Record<string, string>;\n cwd?: string;\n}\n\n/**\n * Response interface for creating sessions\n */\nexport interface CreateSessionResponse extends BaseApiResponse {\n id: string;\n message: string;\n}\n\n/**\n * Request interface for deleting sessions\n */\nexport interface DeleteSessionRequest {\n sessionId: string;\n}\n\n/**\n * Response interface for deleting sessions\n */\nexport interface DeleteSessionResponse extends BaseApiResponse {\n sessionId: string;\n}\n\n/**\n * Client for health checks and utility operations\n */\nexport class UtilityClient extends BaseHttpClient {\n /**\n * Ping the sandbox to check if it's responsive\n */\n async ping(): Promise<string> {\n try {\n const response = await this.get<PingResponse>('/api/ping');\n\n this.logSuccess('Ping successful', response.message);\n return response.message;\n } catch (error) {\n this.logError('ping', error);\n throw error;\n }\n }\n\n /**\n * Get list of available commands in the sandbox environment\n */\n async getCommands(): Promise<string[]> {\n try {\n const response = await this.get<CommandsResponse>('/api/commands');\n\n this.logSuccess(\n 'Commands retrieved',\n `${response.count} commands available`\n );\n\n return response.availableCommands;\n } catch (error) {\n this.logError('getCommands', error);\n throw error;\n }\n }\n\n /**\n * Create a new execution session\n * @param options - Session configuration (id, env, cwd)\n */\n async createSession(\n options: CreateSessionRequest\n ): Promise<CreateSessionResponse> {\n try {\n const response = await this.post<CreateSessionResponse>(\n '/api/session/create',\n options\n );\n\n this.logSuccess('Session created', `ID: ${options.id}`);\n return response;\n } catch (error) {\n this.logError('createSession', error);\n throw error;\n }\n }\n\n /**\n * Delete an execution session\n * @param sessionId - Session ID to delete\n */\n async deleteSession(sessionId: string): Promise<DeleteSessionResponse> {\n try {\n const response = await this.post<DeleteSessionResponse>(\n '/api/session/delete',\n { sessionId }\n );\n\n this.logSuccess('Session deleted', `ID: ${sessionId}`);\n return response;\n } catch (error) {\n this.logError('deleteSession', error);\n throw error;\n }\n }\n\n /**\n * Get the container version\n * Returns the version embedded in the Docker image during build\n */\n async getVersion(): Promise<string> {\n try {\n const response = await this.get<VersionResponse>('/api/version');\n\n this.logSuccess('Version retrieved', response.version);\n return response.version;\n } catch (error) {\n // If version endpoint doesn't exist (old container), return 'unknown'\n // This allows for backward compatibility\n this.logger.debug(\n 'Failed to get container version (may be old container)',\n { error }\n );\n return 'unknown';\n }\n }\n}\n","import { CommandClient } from './command-client';\nimport { FileClient } from './file-client';\nimport { GitClient } from './git-client';\nimport { InterpreterClient } from './interpreter-client';\nimport { PortClient } from './port-client';\nimport { ProcessClient } from './process-client';\nimport type { HttpClientOptions } from './types';\nimport { UtilityClient } from './utility-client';\n\n/**\n * Main sandbox client that composes all domain-specific clients\n * Provides organized access to all sandbox functionality\n */\nexport class SandboxClient {\n public readonly commands: CommandClient;\n public readonly files: FileClient;\n public readonly processes: ProcessClient;\n public readonly ports: PortClient;\n public readonly git: GitClient;\n public readonly interpreter: InterpreterClient;\n public readonly utils: UtilityClient;\n\n constructor(options: HttpClientOptions) {\n // Ensure baseUrl is provided for all clients\n const clientOptions: HttpClientOptions = {\n baseUrl: 'http://localhost:3000',\n ...options\n };\n\n // Initialize all domain clients with shared options\n this.commands = new CommandClient(clientOptions);\n this.files = new FileClient(clientOptions);\n this.processes = new ProcessClient(clientOptions);\n this.ports = new PortClient(clientOptions);\n this.git = new GitClient(clientOptions);\n this.interpreter = new InterpreterClient(clientOptions);\n this.utils = new UtilityClient(clientOptions);\n }\n}\n","/**\n * Security utilities for URL construction and input validation\n *\n * This module contains critical security functions to prevent:\n * - URL injection attacks\n * - SSRF (Server-Side Request Forgery) attacks\n * - DNS rebinding attacks\n * - Host header injection\n * - Open redirect vulnerabilities\n */\n\nexport class SecurityError extends Error {\n constructor(\n message: string,\n public readonly code?: string\n ) {\n super(message);\n this.name = 'SecurityError';\n }\n}\n\n/**\n * Validates port numbers for sandbox services\n * Only allows non-system ports to prevent conflicts and security issues\n */\nexport function validatePort(port: number): boolean {\n // Must be a valid integer\n if (!Number.isInteger(port)) {\n return false;\n }\n\n // Only allow non-system ports (1024-65535)\n if (port < 1024 || port > 65535) {\n return false;\n }\n\n // Exclude ports reserved by our system\n const reservedPorts = [\n 3000, // Control plane port\n 8787 // Common wrangler dev port\n ];\n\n if (reservedPorts.includes(port)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Sanitizes and validates sandbox IDs for DNS compliance and security\n * Only enforces critical requirements - allows maximum developer flexibility\n */\nexport function sanitizeSandboxId(id: string): string {\n // Basic validation: not empty, reasonable length limit (DNS subdomain limit is 63 chars)\n if (!id || id.length > 63) {\n throw new SecurityError(\n 'Sandbox ID must be 1-63 characters long.',\n 'INVALID_SANDBOX_ID_LENGTH'\n );\n }\n\n // DNS compliance: cannot start or end with hyphens (RFC requirement)\n if (id.startsWith('-') || id.endsWith('-')) {\n throw new SecurityError(\n 'Sandbox ID cannot start or end with hyphens (DNS requirement).',\n 'INVALID_SANDBOX_ID_HYPHENS'\n );\n }\n\n // Prevent reserved names that cause technical conflicts\n const reservedNames = [\n 'www',\n 'api',\n 'admin',\n 'root',\n 'system',\n 'cloudflare',\n 'workers'\n ];\n\n const lowerCaseId = id.toLowerCase();\n if (reservedNames.includes(lowerCaseId)) {\n throw new SecurityError(\n `Reserved sandbox ID '${id}' is not allowed.`,\n 'RESERVED_SANDBOX_ID'\n );\n }\n\n return id;\n}\n\n/**\n * Validates language for code interpreter\n * Only allows supported languages\n */\nexport function validateLanguage(language: string | undefined): void {\n if (!language) {\n return; // undefined is valid, will default to python\n }\n\n const supportedLanguages = [\n 'python',\n 'python3',\n 'javascript',\n 'js',\n 'node',\n 'typescript',\n 'ts'\n ];\n const normalized = language.toLowerCase();\n\n if (!supportedLanguages.includes(normalized)) {\n throw new SecurityError(\n `Unsupported language '${language}'. Supported languages: python, javascript, typescript`,\n 'INVALID_LANGUAGE'\n );\n }\n}\n","import {\n type CodeContext,\n type CreateContextOptions,\n Execution,\n type ExecutionError,\n type OutputMessage,\n type Result,\n ResultImpl,\n type RunCodeOptions\n} from '@repo/shared';\nimport type { InterpreterClient } from './clients/interpreter-client.js';\nimport type { Sandbox } from './sandbox.js';\nimport { validateLanguage } from './security.js';\n\nexport class CodeInterpreter {\n private interpreterClient: InterpreterClient;\n private contexts = new Map<string, CodeContext>();\n\n constructor(sandbox: Sandbox) {\n // In init-testing architecture, client is a SandboxClient with an interpreter property\n this.interpreterClient = (sandbox.client as any)\n .interpreter as InterpreterClient;\n }\n\n /**\n * Create a new code execution context\n */\n async createCodeContext(\n options: CreateContextOptions = {}\n ): Promise<CodeContext> {\n // Validate language before sending to container\n validateLanguage(options.language);\n\n const context = await this.interpreterClient.createCodeContext(options);\n this.contexts.set(context.id, context);\n return context;\n }\n\n /**\n * Run code with optional context\n */\n async runCode(\n code: string,\n options: RunCodeOptions = {}\n ): Promise<Execution> {\n // Get or create context\n let context = options.context;\n if (!context) {\n // Try to find or create a default context for the language\n const language = options.language || 'python';\n context = await this.getOrCreateDefaultContext(language);\n }\n\n // Create execution object to collect results\n const execution = new Execution(code, context);\n\n // Stream execution\n await this.interpreterClient.runCodeStream(\n context.id,\n code,\n options.language,\n {\n onStdout: (output: OutputMessage) => {\n execution.logs.stdout.push(output.text);\n if (options.onStdout) return options.onStdout(output);\n },\n onStderr: (output: OutputMessage) => {\n execution.logs.stderr.push(output.text);\n if (options.onStderr) return options.onStderr(output);\n },\n onResult: async (result: Result) => {\n execution.results.push(new ResultImpl(result) as any);\n if (options.onResult) return options.onResult(result);\n },\n onError: (error: ExecutionError) => {\n execution.error = error;\n if (options.onError) return options.onError(error);\n }\n }\n );\n\n return execution;\n }\n\n /**\n * Run code and return a streaming response\n */\n async runCodeStream(\n code: string,\n options: RunCodeOptions = {}\n ): Promise<ReadableStream> {\n // Get or create context\n let context = options.context;\n if (!context) {\n const language = options.language || 'python';\n context = await this.getOrCreateDefaultContext(language);\n }\n\n // Create streaming response\n // Note: doFetch is protected but we need direct access for raw stream response\n const response = await (this.interpreterClient as any).doFetch(\n '/api/execute/code',\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream'\n },\n body: JSON.stringify({\n context_id: context.id,\n code,\n language: options.language\n })\n }\n );\n\n if (!response.ok) {\n const errorData = (await response\n .json()\n .catch(() => ({ error: 'Unknown error' }))) as { error?: string };\n throw new Error(\n errorData.error || `Failed to execute code: ${response.status}`\n );\n }\n\n if (!response.body) {\n throw new Error('No response body for streaming execution');\n }\n\n return response.body;\n }\n\n /**\n * List all code contexts\n */\n async listCodeContexts(): Promise<CodeContext[]> {\n const contexts = await this.interpreterClient.listCodeContexts();\n\n // Update local cache\n for (const context of contexts) {\n this.contexts.set(context.id, context);\n }\n\n return contexts;\n }\n\n /**\n * Delete a code context\n */\n async deleteCodeContext(contextId: string): Promise<void> {\n await this.interpreterClient.deleteCodeContext(contextId);\n this.contexts.delete(contextId);\n }\n\n private async getOrCreateDefaultContext(\n language: 'python' | 'javascript' | 'typescript'\n ): Promise<CodeContext> {\n // Check if we have a cached context for this language\n for (const context of this.contexts.values()) {\n if (context.language === language) {\n return context;\n }\n }\n\n // Create new default context\n return this.createCodeContext({ language });\n }\n}\n","import { switchPort } from '@cloudflare/containers';\nimport { createLogger, type LogContext, TraceContext } from '@repo/shared';\nimport { getSandbox, type Sandbox } from './sandbox';\nimport { sanitizeSandboxId, validatePort } from './security';\n\nexport interface SandboxEnv {\n Sandbox: DurableObjectNamespace<Sandbox>;\n}\n\nexport interface RouteInfo {\n port: number;\n sandboxId: string;\n path: string;\n token: string;\n}\n\nexport async function proxyToSandbox<E extends SandboxEnv>(\n request: Request,\n env: E\n): Promise<Response | null> {\n // Create logger context for this request\n const traceId =\n TraceContext.fromHeaders(request.headers) || TraceContext.generate();\n const logger = createLogger({\n component: 'sandbox-do',\n traceId,\n operation: 'proxy'\n });\n\n try {\n const url = new URL(request.url);\n const routeInfo = extractSandboxRoute(url);\n\n if (!routeInfo) {\n return null; // Not a request to an exposed container port\n }\n\n const { sandboxId, port, path, token } = routeInfo;\n // Preview URLs always use normalized (lowercase) IDs\n const sandbox = getSandbox(env.Sandbox, sandboxId, { normalizeId: true });\n\n // Critical security check: Validate token (mandatory for all user ports)\n // Skip check for control plane port 3000\n if (port !== 3000) {\n // Validate the token matches the port\n const isValidToken = await sandbox.validatePortToken(port, token);\n if (!isValidToken) {\n logger.warn('Invalid token access blocked', {\n port,\n sandboxId,\n path,\n hostname: url.hostname,\n url: request.url,\n method: request.method,\n userAgent: request.headers.get('User-Agent') || 'unknown'\n });\n\n return new Response(\n JSON.stringify({\n error: `Access denied: Invalid token or port not exposed`,\n code: 'INVALID_TOKEN'\n }),\n {\n status: 404,\n headers: {\n 'Content-Type': 'application/json'\n }\n }\n );\n }\n }\n\n // Detect WebSocket upgrade request\n const upgradeHeader = request.headers.get('Upgrade');\n if (upgradeHeader?.toLowerCase() === 'websocket') {\n // WebSocket path: Must use fetch() not containerFetch()\n // This bypasses JSRPC serialization boundary which cannot handle WebSocket upgrades\n return await sandbox.fetch(switchPort(request, port));\n }\n\n // Build proxy request with proper headers\n let proxyUrl: string;\n\n // Route based on the target port\n if (port !== 3000) {\n // Route directly to user's service on the specified port\n proxyUrl = `http://localhost:${port}${path}${url.search}`;\n } else {\n // Port 3000 is our control plane - route normally\n proxyUrl = `http://localhost:3000${path}${url.search}`;\n }\n\n const proxyRequest = new Request(proxyUrl, {\n method: request.method,\n headers: {\n ...Object.fromEntries(request.headers),\n 'X-Original-URL': request.url,\n 'X-Forwarded-Host': url.hostname,\n 'X-Forwarded-Proto': url.protocol.replace(':', ''),\n 'X-Sandbox-Name': sandboxId // Pass the friendly name\n },\n body: request.body,\n // @ts-expect-error - duplex required for body streaming in modern runtimes\n duplex: 'half'\n });\n\n return await sandbox.containerFetch(proxyRequest, port);\n } catch (error) {\n logger.error(\n 'Proxy routing error',\n error instanceof Error ? error : new Error(String(error))\n );\n return new Response('Proxy routing error', { status: 500 });\n }\n}\n\nfunction extractSandboxRoute(url: URL): RouteInfo | null {\n // Parse subdomain pattern: port-sandboxId-token.domain (tokens mandatory)\n // Token is always exactly 16 chars (generated by generatePortToken)\n const subdomainMatch = url.hostname.match(\n /^(\\d{4,5})-([^.-][^.]*?[^.-]|[^.-])-([a-z0-9_-]{16})\\.(.+)$/\n );\n\n if (!subdomainMatch) {\n return null;\n }\n\n const portStr = subdomainMatch[1];\n const sandboxId = subdomainMatch[2];\n const token = subdomainMatch[3]; // Mandatory token\n const domain = subdomainMatch[4];\n\n const port = parseInt(portStr, 10);\n if (!validatePort(port)) {\n return null;\n }\n\n let sanitizedSandboxId: string;\n try {\n sanitizedSandboxId = sanitizeSandboxId(sandboxId);\n } catch (error) {\n return null;\n }\n\n // DNS subdomain length limit is 63 characters\n if (sandboxId.length > 63) {\n return null;\n }\n\n return {\n port,\n sandboxId: sanitizedSandboxId,\n path: url.pathname || '/',\n token\n };\n}\n\nexport function isLocalhostPattern(hostname: string): boolean {\n // Handle IPv6 addresses in brackets (with or without port)\n if (hostname.startsWith('[')) {\n if (hostname.includes(']:')) {\n // [::1]:port format\n const ipv6Part = hostname.substring(0, hostname.indexOf(']:') + 1);\n return ipv6Part === '[::1]';\n } else {\n // [::1] format without port\n return hostname === '[::1]';\n }\n }\n\n // Handle bare IPv6 without brackets\n if (hostname === '::1') {\n return true;\n }\n\n // For IPv4 and regular hostnames, split on colon to remove port\n const hostPart = hostname.split(':')[0];\n\n return (\n hostPart === 'localhost' ||\n hostPart === '127.0.0.1' ||\n hostPart === '0.0.0.0'\n );\n}\n","/**\n * Server-Sent Events (SSE) parser for streaming responses\n * Converts ReadableStream<Uint8Array> to typed AsyncIterable<T>\n */\n\n/**\n * Parse a ReadableStream of SSE events into typed AsyncIterable\n * @param stream - The ReadableStream from fetch response\n * @param signal - Optional AbortSignal for cancellation\n */\nexport async function* parseSSEStream<T>(\n stream: ReadableStream<Uint8Array>,\n signal?: AbortSignal\n): AsyncIterable<T> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n // Check for cancellation\n if (signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n // Decode chunk and add to buffer\n buffer += decoder.decode(value, { stream: true });\n\n // Process complete SSE events in buffer\n const lines = buffer.split('\\n');\n\n // Keep the last incomplete line in buffer\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n // Skip empty lines\n if (line.trim() === '') continue;\n\n // Process SSE data lines\n if (line.startsWith('data: ')) {\n const data = line.substring(6);\n\n // Skip [DONE] markers or empty data\n if (data === '[DONE]' || data.trim() === '') continue;\n\n try {\n const event = JSON.parse(data) as T;\n yield event;\n } catch {\n // Skip invalid JSON events and continue processing\n }\n }\n // Handle other SSE fields if needed (event:, id:, retry:)\n // For now, we only care about data: lines\n }\n }\n\n // Process any remaining data in buffer\n if (buffer.trim() && buffer.startsWith('data: ')) {\n const data = buffer.substring(6);\n if (data !== '[DONE]' && data.trim()) {\n try {\n const event = JSON.parse(data) as T;\n yield event;\n } catch {\n // Skip invalid JSON in final event\n }\n }\n }\n } finally {\n // Clean up resources\n reader.releaseLock();\n }\n}\n\n/**\n * Helper to convert a Response with SSE stream directly to AsyncIterable\n * @param response - Response object with SSE stream\n * @param signal - Optional AbortSignal for cancellation\n */\nexport async function* responseToAsyncIterable<T>(\n response: Response,\n signal?: AbortSignal\n): AsyncIterable<T> {\n if (!response.ok) {\n throw new Error(\n `Response not ok: ${response.status} ${response.statusText}`\n );\n }\n\n if (!response.body) {\n throw new Error('No response body');\n }\n\n yield* parseSSEStream<T>(response.body, signal);\n}\n\n/**\n * Create an SSE-formatted ReadableStream from an AsyncIterable\n * (Useful for Worker endpoints that need to forward AsyncIterable as SSE)\n * @param events - AsyncIterable of events\n * @param options - Stream options\n */\nexport function asyncIterableToSSEStream<T>(\n events: AsyncIterable<T>,\n options?: {\n signal?: AbortSignal;\n serialize?: (event: T) => string;\n }\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n const serialize = options?.serialize || JSON.stringify;\n\n return new ReadableStream({\n async start(controller) {\n try {\n for await (const event of events) {\n if (options?.signal?.aborted) {\n controller.error(new Error('Operation was aborted'));\n break;\n }\n\n const data = serialize(event);\n const sseEvent = `data: ${data}\\n\\n`;\n controller.enqueue(encoder.encode(sseEvent));\n }\n\n // Send completion marker\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\n } catch (error) {\n controller.error(error);\n } finally {\n controller.close();\n }\n },\n\n cancel() {\n // Handle stream cancellation\n }\n });\n}\n","/**\n * Bucket mounting error classes\n *\n * These are SDK-side validation errors that follow the same pattern as SecurityError.\n * They are thrown before any container interaction occurs.\n */\n\nimport { ErrorCode } from '@repo/shared/errors';\n\n/**\n * Base error for bucket mounting operations\n */\nexport class BucketMountError extends Error {\n public readonly code: ErrorCode;\n\n constructor(message: string, code: ErrorCode = ErrorCode.BUCKET_MOUNT_ERROR) {\n super(message);\n this.name = 'BucketMountError';\n this.code = code;\n }\n}\n\n/**\n * Thrown when S3FS mount command fails\n */\nexport class S3FSMountError extends BucketMountError {\n constructor(message: string) {\n super(message, ErrorCode.S3FS_MOUNT_ERROR);\n this.name = 'S3FSMountError';\n }\n}\n\n/**\n * Thrown when no credentials found in environment\n */\nexport class MissingCredentialsError extends BucketMountError {\n constructor(message: string) {\n super(message, ErrorCode.MISSING_CREDENTIALS);\n this.name = 'MissingCredentialsError';\n }\n}\n\n/**\n * Thrown when bucket name, mount path, or options are invalid\n */\nexport class InvalidMountConfigError extends BucketMountError {\n constructor(message: string) {\n super(message, ErrorCode.INVALID_MOUNT_CONFIG);\n this.name = 'InvalidMountConfigError';\n }\n}\n","import type { BucketCredentials, MountBucketOptions } from '@repo/shared';\nimport { MissingCredentialsError } from './errors';\n\n/**\n * Detect credentials for bucket mounting from environment variables\n * Priority order:\n * 1. Explicit options.credentials\n * 2. Standard AWS env vars: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY\n * 3. Error: no credentials found\n *\n * @param options - Mount options\n * @param envVars - Environment variables\n * @returns Detected credentials\n * @throws MissingCredentialsError if no credentials found\n */\nexport function detectCredentials(\n options: MountBucketOptions,\n envVars: Record<string, string | undefined>\n): BucketCredentials {\n // Priority 1: Explicit credentials in options\n if (options.credentials) {\n return options.credentials;\n }\n\n // Priority 2: Standard AWS env vars\n const awsAccessKeyId = envVars.AWS_ACCESS_KEY_ID;\n const awsSecretAccessKey = envVars.AWS_SECRET_ACCESS_KEY;\n\n if (awsAccessKeyId && awsSecretAccessKey) {\n return {\n accessKeyId: awsAccessKeyId,\n secretAccessKey: awsSecretAccessKey\n };\n }\n\n // No credentials found - throw error with helpful message\n throw new MissingCredentialsError(\n `No credentials found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY ` +\n `environment variables, or pass explicit credentials in options.`\n );\n}\n","/**\n * Provider detection and s3fs flag configuration\n *\n * Based on s3fs-fuse documentation:\n * https://github.com/s3fs-fuse/s3fs-fuse/wiki/Non-Amazon-S3\n */\n\nimport type { BucketProvider } from '@repo/shared';\n\n/**\n * Detect provider from endpoint URL using pattern matching\n */\nexport function detectProviderFromUrl(endpoint: string): BucketProvider | null {\n try {\n const url = new URL(endpoint);\n const hostname = url.hostname.toLowerCase();\n\n if (hostname.endsWith('.r2.cloudflarestorage.com')) {\n return 'r2';\n }\n\n // Match AWS S3: *.amazonaws.com or s3.amazonaws.com\n if (\n hostname.endsWith('.amazonaws.com') ||\n hostname === 's3.amazonaws.com'\n ) {\n return 's3';\n }\n\n if (hostname === 'storage.googleapis.com') {\n return 'gcs';\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Get s3fs flags for a given provider\n *\n * Based on s3fs-fuse wiki recommendations:\n * https://github.com/s3fs-fuse/s3fs-fuse/wiki/Non-Amazon-S3\n */\nexport function getProviderFlags(provider: BucketProvider | null): string[] {\n if (!provider) {\n return ['use_path_request_style'];\n }\n\n switch (provider) {\n case 'r2':\n return ['nomixupload'];\n\n case 's3':\n return [];\n\n case 'gcs':\n return [];\n\n default:\n return ['use_path_request_style'];\n }\n}\n\n/**\n * Resolve s3fs options by combining provider defaults with user overrides\n */\nexport function resolveS3fsOptions(\n provider: BucketProvider | null,\n userOptions?: string[]\n): string[] {\n const providerFlags = getProviderFlags(provider);\n\n if (!userOptions || userOptions.length === 0) {\n return providerFlags;\n }\n\n // Merge provider flags with user options\n // User options take precedence (come last in the array)\n const allFlags = [...providerFlags, ...userOptions];\n\n // Deduplicate flags (keep last occurrence)\n const flagMap = new Map<string, string>();\n\n for (const flag of allFlags) {\n // Split on '=' to get the flag name\n const [flagName] = flag.split('=');\n flagMap.set(flagName, flag);\n }\n\n return Array.from(flagMap.values());\n}\n","/**\n * SDK version - automatically synchronized with package.json by Changesets\n * This file is auto-updated by .github/changeset-version.ts during releases\n * DO NOT EDIT MANUALLY - Changes will be overwritten on the next version bump\n */\nexport const SDK_VERSION = '0.5.3';\n","import { Container, getContainer, switchPort } from '@cloudflare/containers';\nimport type {\n BucketCredentials,\n BucketProvider,\n CodeContext,\n CreateContextOptions,\n ExecEvent,\n ExecOptions,\n ExecResult,\n ExecutionResult,\n ExecutionSession,\n ISandbox,\n MountBucketOptions,\n Process,\n ProcessOptions,\n ProcessStatus,\n RunCodeOptions,\n SandboxOptions,\n SessionOptions,\n StreamOptions\n} from '@repo/shared';\nimport {\n createLogger,\n getEnvString,\n type SessionDeleteResult,\n shellEscape,\n TraceContext\n} from '@repo/shared';\nimport { type ExecuteResponse, SandboxClient } from './clients';\nimport type { ErrorResponse } from './errors';\nimport { CustomDomainRequiredError, ErrorCode } from './errors';\nimport { CodeInterpreter } from './interpreter';\nimport { isLocalhostPattern } from './request-handler';\nimport { SecurityError, sanitizeSandboxId, validatePort } from './security';\nimport { parseSSEStream } from './sse-parser';\nimport {\n detectCredentials,\n detectProviderFromUrl,\n resolveS3fsOptions\n} from './storage-mount';\nimport {\n InvalidMountConfigError,\n S3FSMountError\n} from './storage-mount/errors';\nimport type { MountInfo } from './storage-mount/types';\nimport { SDK_VERSION } from './version';\n\nexport function getSandbox(\n ns: DurableObjectNamespace<Sandbox>,\n id: string,\n options?: SandboxOptions\n): Sandbox {\n const sanitizedId = sanitizeSandboxId(id);\n const effectiveId = options?.normalizeId\n ? sanitizedId.toLowerCase()\n : sanitizedId;\n\n const hasUppercase = /[A-Z]/.test(sanitizedId);\n if (!options?.normalizeId && hasUppercase) {\n const logger = createLogger({ component: 'sandbox-do' });\n logger.warn(\n `Sandbox ID \"${sanitizedId}\" contains uppercase letters, which causes issues with preview URLs (hostnames are case-insensitive). ` +\n `normalizeId will default to true in a future version to prevent this. ` +\n `Use lowercase IDs or pass { normalizeId: true } to prepare.`\n );\n }\n\n const stub = getContainer(ns, effectiveId) as unknown as Sandbox;\n\n stub.setSandboxName?.(effectiveId, options?.normalizeId);\n\n if (options?.baseUrl) {\n stub.setBaseUrl(options.baseUrl);\n }\n\n if (options?.sleepAfter !== undefined) {\n stub.setSleepAfter(options.sleepAfter);\n }\n\n if (options?.keepAlive !== undefined) {\n stub.setKeepAlive(options.keepAlive);\n }\n\n if (options?.containerTimeouts) {\n stub.setContainerTimeouts(options.containerTimeouts);\n }\n\n return Object.assign(stub, {\n wsConnect: connect(stub)\n });\n}\n\nexport function connect(stub: {\n fetch: (request: Request) => Promise<Response>;\n}) {\n return async (request: Request, port: number) => {\n if (!validatePort(port)) {\n throw new SecurityError(\n `Invalid or restricted port: ${port}. Ports must be in range 1024-65535 and not reserved.`\n );\n }\n const portSwitchedRequest = switchPort(request, port);\n return await stub.fetch(portSwitchedRequest);\n };\n}\n\nexport class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {\n defaultPort = 3000; // Default port for the container's Bun server\n sleepAfter: string | number = '10m'; // Sleep the sandbox if no requests are made in this timeframe\n\n client: SandboxClient;\n private codeInterpreter: CodeInterpreter;\n private sandboxName: string | null = null;\n private normalizeId: boolean = false;\n private baseUrl: string | null = null;\n private portTokens: Map<number, string> = new Map();\n private defaultSession: string | null = null;\n envVars: Record<string, string> = {};\n private logger: ReturnType<typeof createLogger>;\n private keepAliveEnabled: boolean = false;\n private activeMounts: Map<string, MountInfo> = new Map();\n\n /**\n * Default container startup timeouts (conservative for production)\n * Based on Cloudflare docs: \"Containers take several minutes to provision\"\n */\n private readonly DEFAULT_CONTAINER_TIMEOUTS = {\n // Time to get container instance and launch VM\n // @cloudflare/containers default: 8s (too short for cold starts)\n instanceGetTimeoutMS: 30_000, // 30 seconds\n\n // Time for application to start and ports to be ready\n // @cloudflare/containers default: 20s\n portReadyTimeoutMS: 90_000, // 90 seconds (allows for heavy containers)\n\n // Polling interval for checking container readiness\n // @cloudflare/containers default: 300ms (too aggressive)\n waitIntervalMS: 1000 // 1 second (reduces load)\n };\n\n /**\n * Active container timeout configuration\n * Can be set via options, env vars, or defaults\n */\n private containerTimeouts = { ...this.DEFAULT_CONTAINER_TIMEOUTS };\n\n constructor(ctx: DurableObjectState<{}>, env: Env) {\n super(ctx, env);\n\n const envObj = env as Record<string, unknown>;\n // Set sandbox environment variables from env object\n const sandboxEnvKeys = ['SANDBOX_LOG_LEVEL', 'SANDBOX_LOG_FORMAT'] as const;\n sandboxEnvKeys.forEach((key) => {\n if (envObj?.[key]) {\n this.envVars[key] = String(envObj[key]);\n }\n });\n\n // Initialize timeouts with env var fallbacks\n this.containerTimeouts = this.getDefaultTimeouts(envObj);\n\n this.logger = createLogger({\n component: 'sandbox-do',\n sandboxId: this.ctx.id.toString()\n });\n\n this.client = new SandboxClient({\n logger: this.logger,\n port: 3000, // Control plane port\n stub: this\n });\n\n // Initialize code interpreter - pass 'this' after client is ready\n // The CodeInterpreter extracts client.interpreter from the sandbox\n this.codeInterpreter = new CodeInterpreter(this);\n\n this.ctx.blockConcurrencyWhile(async () => {\n this.sandboxName =\n (await this.ctx.storage.get<string>('sandboxName')) || null;\n this.normalizeId =\n (await this.ctx.storage.get<boolean>('normalizeId')) || false;\n this.defaultSession =\n (await this.ctx.storage.get<string>('defaultSession')) || null;\n const storedTokens =\n (await this.ctx.storage.get<Record<string, string>>('portTokens')) ||\n {};\n\n // Convert stored tokens back to Map\n this.portTokens = new Map();\n for (const [portStr, token] of Object.entries(storedTokens)) {\n this.portTokens.set(parseInt(portStr, 10), token);\n }\n\n // Load saved timeout configuration (highest priority)\n const storedTimeouts =\n await this.ctx.storage.get<\n NonNullable<SandboxOptions['containerTimeouts']>\n >('containerTimeouts');\n if (storedTimeouts) {\n this.containerTimeouts = {\n ...this.containerTimeouts,\n ...storedTimeouts\n };\n }\n });\n }\n\n async setSandboxName(name: string, normalizeId?: boolean): Promise<void> {\n if (!this.sandboxName) {\n this.sandboxName = name;\n this.normalizeId = normalizeId || false;\n await this.ctx.storage.put('sandboxName', name);\n await this.ctx.storage.put('normalizeId', this.normalizeId);\n }\n }\n\n // RPC method to set the base URL\n async setBaseUrl(baseUrl: string): Promise<void> {\n if (!this.baseUrl) {\n this.baseUrl = baseUrl;\n await this.ctx.storage.put('baseUrl', baseUrl);\n } else {\n if (this.baseUrl !== baseUrl) {\n throw new Error(\n 'Base URL already set and different from one previously provided'\n );\n }\n }\n }\n\n // RPC method to set the sleep timeout\n async setSleepAfter(sleepAfter: string | number): Promise<void> {\n this.sleepAfter = sleepAfter;\n }\n\n // RPC method to enable keepAlive mode\n async setKeepAlive(keepAlive: boolean): Promise<void> {\n this.keepAliveEnabled = keepAlive;\n if (keepAlive) {\n this.logger.info(\n 'KeepAlive mode enabled - container will stay alive until explicitly destroyed'\n );\n } else {\n this.logger.info(\n 'KeepAlive mode disabled - container will timeout normally'\n );\n }\n }\n\n // RPC method to set environment variables\n async setEnvVars(envVars: Record<string, string>): Promise<void> {\n // Update local state for new sessions\n this.envVars = { ...this.envVars, ...envVars };\n\n // If default session already exists, update it directly\n if (this.defaultSession) {\n // Set environment variables by executing export commands in the existing session\n for (const [key, value] of Object.entries(envVars)) {\n const escapedValue = value.replace(/'/g, \"'\\\\''\");\n const exportCommand = `export ${key}='${escapedValue}'`;\n\n const result = await this.client.commands.execute(\n exportCommand,\n this.defaultSession\n );\n\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to set ${key}: ${result.stderr || 'Unknown error'}`\n );\n }\n }\n }\n }\n\n /**\n * RPC method to configure container startup timeouts\n */\n async setContainerTimeouts(\n timeouts: NonNullable<SandboxOptions['containerTimeouts']>\n ): Promise<void> {\n const validated = { ...this.containerTimeouts };\n\n // Validate each timeout if provided\n if (timeouts.instanceGetTimeoutMS !== undefined) {\n validated.instanceGetTimeoutMS = this.validateTimeout(\n timeouts.instanceGetTimeoutMS,\n 'instanceGetTimeoutMS',\n 5_000,\n 300_000\n );\n }\n\n if (timeouts.portReadyTimeoutMS !== undefined) {\n validated.portReadyTimeoutMS = this.validateTimeout(\n timeouts.portReadyTimeoutMS,\n 'portReadyTimeoutMS',\n 10_000,\n 600_000\n );\n }\n\n if (timeouts.waitIntervalMS !== undefined) {\n validated.waitIntervalMS = this.validateTimeout(\n timeouts.waitIntervalMS,\n 'waitIntervalMS',\n 100,\n 5_000\n );\n }\n\n this.containerTimeouts = validated;\n\n // Persist to storage\n await this.ctx.storage.put('containerTimeouts', this.containerTimeouts);\n\n this.logger.debug('Container timeouts updated', this.containerTimeouts);\n }\n\n /**\n * Validate a timeout value is within acceptable range\n * Throws error if invalid - used for user-provided values\n */\n private validateTimeout(\n value: number,\n name: string,\n min: number,\n max: number\n ): number {\n if (\n typeof value !== 'number' ||\n Number.isNaN(value) ||\n !Number.isFinite(value)\n ) {\n throw new Error(`${name} must be a valid finite number, got ${value}`);\n }\n\n if (value < min || value > max) {\n throw new Error(\n `${name} must be between ${min}-${max}ms, got ${value}ms`\n );\n }\n\n return value;\n }\n\n /**\n * Get default timeouts with env var fallbacks and validation\n * Precedence: SDK defaults < Env vars < User config\n */\n private getDefaultTimeouts(\n env: Record<string, unknown>\n ): typeof this.DEFAULT_CONTAINER_TIMEOUTS {\n const parseAndValidate = (\n envVar: string | undefined,\n name: keyof typeof this.DEFAULT_CONTAINER_TIMEOUTS,\n min: number,\n max: number\n ): number => {\n const defaultValue = this.DEFAULT_CONTAINER_TIMEOUTS[name];\n\n if (envVar === undefined) {\n return defaultValue;\n }\n\n const parsed = parseInt(envVar, 10);\n\n if (Number.isNaN(parsed)) {\n this.logger.warn(\n `Invalid ${name}: \"${envVar}\" is not a number. Using default: ${defaultValue}ms`\n );\n return defaultValue;\n }\n\n if (parsed < min || parsed > max) {\n this.logger.warn(\n `Invalid ${name}: ${parsed}ms. Must be ${min}-${max}ms. Using default: ${defaultValue}ms`\n );\n return defaultValue;\n }\n\n return parsed;\n };\n\n return {\n instanceGetTimeoutMS: parseAndValidate(\n getEnvString(env, 'SANDBOX_INSTANCE_TIMEOUT_MS'),\n 'instanceGetTimeoutMS',\n 5_000, // Min 5s\n 300_000 // Max 5min\n ),\n portReadyTimeoutMS: parseAndValidate(\n getEnvString(env, 'SANDBOX_PORT_TIMEOUT_MS'),\n 'portReadyTimeoutMS',\n 10_000, // Min 10s\n 600_000 // Max 10min\n ),\n waitIntervalMS: parseAndValidate(\n getEnvString(env, 'SANDBOX_POLL_INTERVAL_MS'),\n 'waitIntervalMS',\n 100, // Min 100ms\n 5_000 // Max 5s\n )\n };\n }\n\n /*\n * Mount an S3-compatible bucket as a local directory using S3FS-FUSE\n *\n * Requires explicit endpoint URL. Credentials are auto-detected from environment\n * variables or can be provided explicitly.\n *\n * @param bucket - Bucket name\n * @param mountPath - Absolute path in container to mount at\n * @param options - Configuration options with required endpoint\n * @throws MissingCredentialsError if no credentials found in environment\n * @throws S3FSMountError if S3FS mount command fails\n * @throws InvalidMountConfigError if bucket name, mount path, or endpoint is invalid\n */\n async mountBucket(\n bucket: string,\n mountPath: string,\n options: MountBucketOptions\n ): Promise<void> {\n this.logger.info(`Mounting bucket ${bucket} to ${mountPath}`);\n\n // Validate options\n this.validateMountOptions(bucket, mountPath, options);\n\n // Detect provider from explicit option or URL pattern\n const provider: BucketProvider | null =\n options.provider || detectProviderFromUrl(options.endpoint);\n\n this.logger.debug(`Detected provider: ${provider || 'unknown'}`, {\n explicitProvider: options.provider\n });\n\n // Detect credentials\n const credentials = detectCredentials(options, this.envVars);\n\n // Generate unique password file path\n const passwordFilePath = this.generatePasswordFilePath();\n\n // Reserve mount path immediately to prevent race conditions\n // (two concurrent mount calls would both pass validation otherwise)\n this.activeMounts.set(mountPath, {\n bucket,\n mountPath,\n endpoint: options.endpoint,\n provider,\n passwordFilePath,\n mounted: false\n });\n\n try {\n // Create password file with credentials\n await this.createPasswordFile(passwordFilePath, bucket, credentials);\n\n // Create mount directory\n await this.exec(`mkdir -p ${shellEscape(mountPath)}`);\n\n // Execute S3FS mount with password file\n await this.executeS3FSMount(\n bucket,\n mountPath,\n options,\n provider,\n passwordFilePath\n );\n\n // Mark as successfully mounted\n this.activeMounts.set(mountPath, {\n bucket,\n mountPath,\n endpoint: options.endpoint,\n provider,\n passwordFilePath,\n mounted: true\n });\n\n this.logger.info(`Successfully mounted bucket ${bucket} to ${mountPath}`);\n } catch (error) {\n // Clean up password file on failure\n await this.deletePasswordFile(passwordFilePath);\n\n // Clean up reservation on failure\n this.activeMounts.delete(mountPath);\n throw error;\n }\n }\n\n /**\n * Manually unmount a bucket filesystem\n *\n * @param mountPath - Absolute path where the bucket is mounted\n * @throws InvalidMountConfigError if mount path doesn't exist or isn't mounted\n */\n async unmountBucket(mountPath: string): Promise<void> {\n this.logger.info(`Unmounting bucket from ${mountPath}`);\n\n // Look up mount by path\n const mountInfo = this.activeMounts.get(mountPath);\n\n // Throw error if mount doesn't exist\n if (!mountInfo) {\n throw new InvalidMountConfigError(\n `No active mount found at path: ${mountPath}`\n );\n }\n\n // Unmount the filesystem\n try {\n await this.exec(`fusermount -u ${shellEscape(mountPath)}`);\n mountInfo.mounted = false;\n\n // Only remove from tracking if unmount succeeded\n this.activeMounts.delete(mountPath);\n } finally {\n // Always cleanup password file, even if unmount fails\n await this.deletePasswordFile(mountInfo.passwordFilePath);\n }\n\n this.logger.info(`Successfully unmounted bucket from ${mountPath}`);\n }\n\n /**\n * Validate mount options\n */\n private validateMountOptions(\n bucket: string,\n mountPath: string,\n options: MountBucketOptions\n ): void {\n // Require endpoint field\n if (!options.endpoint) {\n throw new InvalidMountConfigError(\n 'Endpoint is required. Provide the full S3-compatible endpoint URL.'\n );\n }\n\n // Basic URL validation\n try {\n new URL(options.endpoint);\n } catch (error) {\n throw new InvalidMountConfigError(\n `Invalid endpoint URL: \"${options.endpoint}\". Must be a valid HTTP(S) URL.`\n );\n }\n\n // Validate bucket name (S3-compatible naming rules)\n const bucketNameRegex = /^[a-z0-9]([a-z0-9.-]{0,61}[a-z0-9])?$/;\n if (!bucketNameRegex.test(bucket)) {\n throw new InvalidMountConfigError(\n `Invalid bucket name: \"${bucket}\". Bucket names must be 3-63 characters, ` +\n `lowercase alphanumeric, dots, or hyphens, and cannot start/end with dots or hyphens.`\n );\n }\n\n // Validate mount path is absolute\n if (!mountPath.startsWith('/')) {\n throw new InvalidMountConfigError(\n `Mount path must be absolute (start with /): \"${mountPath}\"`\n );\n }\n\n // Check for duplicate mount path\n if (this.activeMounts.has(mountPath)) {\n const existingMount = this.activeMounts.get(mountPath);\n throw new InvalidMountConfigError(\n `Mount path \"${mountPath}\" is already in use by bucket \"${existingMount?.bucket}\". ` +\n `Unmount the existing bucket first or use a different mount path.`\n );\n }\n }\n\n /**\n * Generate unique password file path for s3fs credentials\n */\n private generatePasswordFilePath(): string {\n const uuid = crypto.randomUUID();\n return `/tmp/.passwd-s3fs-${uuid}`;\n }\n\n /**\n * Create password file with s3fs credentials\n * Format: bucket:accessKeyId:secretAccessKey\n */\n private async createPasswordFile(\n passwordFilePath: string,\n bucket: string,\n credentials: BucketCredentials\n ): Promise<void> {\n const content = `${bucket}:${credentials.accessKeyId}:${credentials.secretAccessKey}`;\n\n await this.writeFile(passwordFilePath, content);\n\n await this.exec(`chmod 0600 ${shellEscape(passwordFilePath)}`);\n\n this.logger.debug(`Created password file: ${passwordFilePath}`);\n }\n\n /**\n * Delete password file\n */\n private async deletePasswordFile(passwordFilePath: string): Promise<void> {\n try {\n await this.exec(`rm -f ${shellEscape(passwordFilePath)}`);\n this.logger.debug(`Deleted password file: ${passwordFilePath}`);\n } catch (error) {\n this.logger.warn(`Failed to delete password file ${passwordFilePath}`, {\n error: error instanceof Error ? error.message : String(error)\n });\n }\n }\n\n /**\n * Execute S3FS mount command\n */\n private async executeS3FSMount(\n bucket: string,\n mountPath: string,\n options: MountBucketOptions,\n provider: BucketProvider | null,\n passwordFilePath: string\n ): Promise<void> {\n // Resolve s3fs options (provider defaults + user overrides)\n const resolvedOptions = resolveS3fsOptions(provider, options.s3fsOptions);\n\n // Build s3fs mount command\n const s3fsArgs: string[] = [];\n\n // Add password file option FIRST\n s3fsArgs.push(`passwd_file=${passwordFilePath}`);\n\n // Add resolved provider-specific and user options\n s3fsArgs.push(...resolvedOptions);\n\n // Add read-only flag if requested\n if (options.readOnly) {\n s3fsArgs.push('ro');\n }\n\n // Add endpoint URL\n s3fsArgs.push(`url=${options.endpoint}`);\n\n // Build final command with escaped options\n const optionsStr = shellEscape(s3fsArgs.join(','));\n const mountCmd = `s3fs ${shellEscape(bucket)} ${shellEscape(mountPath)} -o ${optionsStr}`;\n\n this.logger.debug('Executing s3fs mount', {\n bucket,\n mountPath,\n provider,\n resolvedOptions\n });\n\n // Execute mount command\n const result = await this.exec(mountCmd);\n\n if (result.exitCode !== 0) {\n throw new S3FSMountError(\n `S3FS mount failed: ${result.stderr || result.stdout || 'Unknown error'}`\n );\n }\n\n this.logger.debug('Mount command executed successfully');\n }\n\n /**\n * Cleanup and destroy the sandbox container\n */\n override async destroy(): Promise<void> {\n this.logger.info('Destroying sandbox container');\n\n // Unmount all mounted buckets and cleanup password files\n for (const [mountPath, mountInfo] of this.activeMounts.entries()) {\n if (mountInfo.mounted) {\n try {\n this.logger.info(\n `Unmounting bucket ${mountInfo.bucket} from ${mountPath}`\n );\n await this.exec(`fusermount -u ${shellEscape(mountPath)}`);\n mountInfo.mounted = false;\n } catch (error) {\n const errorMsg =\n error instanceof Error ? error.message : String(error);\n this.logger.warn(\n `Failed to unmount bucket ${mountInfo.bucket} from ${mountPath}: ${errorMsg}`\n );\n }\n }\n\n // Always cleanup password file\n await this.deletePasswordFile(mountInfo.passwordFilePath);\n }\n\n await super.destroy();\n }\n\n override onStart() {\n this.logger.debug('Sandbox started');\n\n // Check version compatibility asynchronously (don't block startup)\n this.checkVersionCompatibility().catch((error) => {\n this.logger.error(\n 'Version compatibility check failed',\n error instanceof Error ? error : new Error(String(error))\n );\n });\n }\n\n /**\n * Check if the container version matches the SDK version\n * Logs a warning if there's a mismatch\n */\n private async checkVersionCompatibility(): Promise<void> {\n try {\n // Get the SDK version (imported from version.ts)\n const sdkVersion = SDK_VERSION;\n\n // Get container version\n const containerVersion = await this.client.utils.getVersion();\n\n // If container version is unknown, it's likely an old container without the endpoint\n if (containerVersion === 'unknown') {\n this.logger.warn(\n 'Container version check: Container version could not be determined. ' +\n 'This may indicate an outdated container image. ' +\n 'Please update your container to match SDK version ' +\n sdkVersion\n );\n return;\n }\n\n // Check if versions match\n if (containerVersion !== sdkVersion) {\n const message =\n `Version mismatch detected! SDK version (${sdkVersion}) does not match ` +\n `container version (${containerVersion}). This may cause compatibility issues. ` +\n `Please update your container image to version ${sdkVersion}`;\n\n // Log warning - we can't reliably detect dev vs prod environment in Durable Objects\n // so we always use warning level as requested by the user\n this.logger.warn(message);\n } else {\n this.logger.debug('Version check passed', {\n sdkVersion,\n containerVersion\n });\n }\n } catch (error) {\n // Don't fail the sandbox initialization if version check fails\n this.logger.debug('Version compatibility check encountered an error', {\n error: error instanceof Error ? error.message : String(error)\n });\n }\n }\n\n override async onStop() {\n this.logger.debug('Sandbox stopped');\n\n // Clear in-memory state that references the old container\n // This prevents stale references after container restarts\n this.portTokens.clear();\n this.defaultSession = null;\n this.activeMounts.clear();\n\n // Persist cleanup to storage so state is clean on next container start\n await Promise.all([\n this.ctx.storage.delete('portTokens'),\n this.ctx.storage.delete('defaultSession')\n ]);\n }\n\n override onError(error: unknown) {\n this.logger.error(\n 'Sandbox error',\n error instanceof Error ? error : new Error(String(error))\n );\n }\n\n /**\n * Override Container.containerFetch to use production-friendly timeouts\n * Automatically starts container with longer timeouts if not running\n */\n override async containerFetch(\n requestOrUrl: Request | string | URL,\n portOrInit?: number | RequestInit,\n portParam?: number\n ): Promise<Response> {\n // Parse arguments to extract request and port\n const { request, port } = this.parseContainerFetchArgs(\n requestOrUrl,\n portOrInit,\n portParam\n );\n\n const state = await this.getState();\n\n // If container not healthy, start it with production timeouts\n if (state.status !== 'healthy') {\n try {\n this.logger.debug('Starting container with configured timeouts', {\n instanceTimeout: this.containerTimeouts.instanceGetTimeoutMS,\n portTimeout: this.containerTimeouts.portReadyTimeoutMS\n });\n\n await this.startAndWaitForPorts({\n ports: port,\n cancellationOptions: {\n instanceGetTimeoutMS: this.containerTimeouts.instanceGetTimeoutMS,\n portReadyTimeoutMS: this.containerTimeouts.portReadyTimeoutMS,\n waitInterval: this.containerTimeouts.waitIntervalMS,\n abort: request.signal\n }\n });\n } catch (e) {\n // Handle provisioning vs startup errors\n if (this.isNoInstanceError(e)) {\n return new Response(\n 'Container is currently provisioning. This can take several minutes on first deployment. Please retry in a moment.',\n {\n status: 503,\n headers: { 'Retry-After': '10' } // Suggest 10s retry\n }\n );\n }\n\n // Other startup errors\n this.logger.error(\n 'Container startup failed',\n e instanceof Error ? e : new Error(String(e))\n );\n return new Response(\n `Failed to start container: ${e instanceof Error ? e.message : String(e)}`,\n { status: 500 }\n );\n }\n }\n\n // Delegate to parent for the actual fetch (handles TCP port access internally)\n return await super.containerFetch(requestOrUrl, portOrInit, portParam);\n }\n\n /**\n * Helper: Check if error is \"no container instance available\"\n */\n private isNoInstanceError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.toLowerCase().includes('no container instance')\n );\n }\n\n /**\n * Helper: Parse containerFetch arguments (supports multiple signatures)\n */\n private parseContainerFetchArgs(\n requestOrUrl: Request | string | URL,\n portOrInit?: number | RequestInit,\n portParam?: number\n ): { request: Request; port: number } {\n let request: Request;\n let port: number | undefined;\n\n if (requestOrUrl instanceof Request) {\n request = requestOrUrl;\n port = typeof portOrInit === 'number' ? portOrInit : undefined;\n } else {\n const url =\n typeof requestOrUrl === 'string'\n ? requestOrUrl\n : requestOrUrl.toString();\n const init = typeof portOrInit === 'number' ? {} : portOrInit || {};\n port =\n typeof portOrInit === 'number'\n ? portOrInit\n : typeof portParam === 'number'\n ? portParam\n : undefined;\n request = new Request(url, init);\n }\n\n port ??= this.defaultPort;\n\n if (port === undefined) {\n throw new Error('No port specified for container fetch');\n }\n\n return { request, port };\n }\n\n /**\n * Override onActivityExpired to prevent automatic shutdown when keepAlive is enabled\n * When keepAlive is disabled, calls parent implementation which stops the container\n */\n override async onActivityExpired(): Promise<void> {\n if (this.keepAliveEnabled) {\n this.logger.debug(\n 'Activity expired but keepAlive is enabled - container will stay alive'\n );\n // Do nothing - don't call stop(), container stays alive\n } else {\n // Default behavior: stop the container\n this.logger.debug('Activity expired - stopping container');\n await super.onActivityExpired();\n }\n }\n\n // Override fetch to route internal container requests to appropriate ports\n override async fetch(request: Request): Promise<Response> {\n // Extract or generate trace ID from request\n const traceId =\n TraceContext.fromHeaders(request.headers) || TraceContext.generate();\n\n // Create request-specific logger with trace ID\n const requestLogger = this.logger.child({ traceId, operation: 'fetch' });\n\n const url = new URL(request.url);\n\n // Capture and store the sandbox name from the header if present\n if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {\n const name = request.headers.get('X-Sandbox-Name')!;\n this.sandboxName = name;\n await this.ctx.storage.put('sandboxName', name);\n }\n\n // Detect WebSocket upgrade request (RFC 6455 compliant)\n const upgradeHeader = request.headers.get('Upgrade');\n const connectionHeader = request.headers.get('Connection');\n const isWebSocket =\n upgradeHeader?.toLowerCase() === 'websocket' &&\n connectionHeader?.toLowerCase().includes('upgrade');\n\n if (isWebSocket) {\n // WebSocket path: Let parent Container class handle WebSocket proxying\n // This bypasses containerFetch() which uses JSRPC and cannot handle WebSocket upgrades\n try {\n requestLogger.debug('WebSocket upgrade requested', {\n path: url.pathname,\n port: this.determinePort(url)\n });\n return await super.fetch(request);\n } catch (error) {\n requestLogger.error(\n 'WebSocket connection failed',\n error instanceof Error ? error : new Error(String(error)),\n { path: url.pathname }\n );\n throw error;\n }\n }\n\n // Non-WebSocket: Use existing port determination and HTTP routing logic\n const port = this.determinePort(url);\n\n // Route to the appropriate port\n return await this.containerFetch(request, port);\n }\n\n wsConnect(request: Request, port: number): Promise<Response> {\n // Dummy implementation that will be overridden by the stub\n throw new Error('Not implemented here to avoid RPC serialization issues');\n }\n\n private determinePort(url: URL): number {\n // Extract port from proxy requests (e.g., /proxy/8080/*)\n const proxyMatch = url.pathname.match(/^\\/proxy\\/(\\d+)/);\n if (proxyMatch) {\n return parseInt(proxyMatch[1], 10);\n }\n\n // All other requests go to control plane on port 3000\n // This includes /api/* endpoints and any other control requests\n return 3000;\n }\n\n /**\n * Ensure default session exists - lazy initialization\n * This is called automatically by all public methods that need a session\n *\n * The session is persisted to Durable Object storage to survive hot reloads\n * during development. If a session already exists in the container after reload,\n * we reuse it instead of trying to create a new one.\n */\n private async ensureDefaultSession(): Promise<string> {\n if (!this.defaultSession) {\n const sessionId = `sandbox-${this.sandboxName || 'default'}`;\n\n try {\n // Try to create session in container\n await this.client.utils.createSession({\n id: sessionId,\n env: this.envVars || {},\n cwd: '/workspace'\n });\n\n this.defaultSession = sessionId;\n // Persist to storage so it survives hot reloads\n await this.ctx.storage.put('defaultSession', sessionId);\n this.logger.debug('Default session initialized', { sessionId });\n } catch (error: unknown) {\n // If session already exists (e.g., after hot reload), reuse it\n if (\n error instanceof Error &&\n error.message.includes('already exists')\n ) {\n this.logger.debug('Reusing existing session after reload', {\n sessionId\n });\n this.defaultSession = sessionId;\n // Persist to storage in case it wasn't saved before\n await this.ctx.storage.put('defaultSession', sessionId);\n } else {\n // Re-throw other errors\n throw error;\n }\n }\n }\n return this.defaultSession;\n }\n\n // Enhanced exec method - always returns ExecResult with optional streaming\n // This replaces the old exec method to match ISandbox interface\n async exec(command: string, options?: ExecOptions): Promise<ExecResult> {\n const session = await this.ensureDefaultSession();\n return this.execWithSession(command, session, options);\n }\n\n /**\n * Internal session-aware exec implementation\n * Used by both public exec() and session wrappers\n */\n private async execWithSession(\n command: string,\n sessionId: string,\n options?: ExecOptions\n ): Promise<ExecResult> {\n const startTime = Date.now();\n const timestamp = new Date().toISOString();\n\n let timeoutId: NodeJS.Timeout | undefined;\n\n try {\n // Handle cancellation\n if (options?.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n let result: ExecResult;\n\n if (options?.stream && options?.onOutput) {\n // Streaming with callbacks - we need to collect the final result\n result = await this.executeWithStreaming(\n command,\n sessionId,\n options,\n startTime,\n timestamp\n );\n } else {\n // Regular execution with session\n const commandOptions =\n options &&\n (options.timeout !== undefined ||\n options.env !== undefined ||\n options.cwd !== undefined)\n ? {\n timeoutMs: options.timeout,\n env: options.env,\n cwd: options.cwd\n }\n : undefined;\n\n const response = await this.client.commands.execute(\n command,\n sessionId,\n commandOptions\n );\n\n const duration = Date.now() - startTime;\n result = this.mapExecuteResponseToExecResult(\n response,\n duration,\n sessionId\n );\n }\n\n // Call completion callback if provided\n if (options?.onComplete) {\n options.onComplete(result);\n }\n\n return result;\n } catch (error) {\n if (options?.onError && error instanceof Error) {\n options.onError(error);\n }\n throw error;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n\n private async executeWithStreaming(\n command: string,\n sessionId: string,\n options: ExecOptions,\n startTime: number,\n timestamp: string\n ): Promise<ExecResult> {\n let stdout = '';\n let stderr = '';\n\n try {\n const stream = await this.client.commands.executeStream(\n command,\n sessionId,\n {\n timeoutMs: options.timeout,\n env: options.env,\n cwd: options.cwd\n }\n );\n\n for await (const event of parseSSEStream<ExecEvent>(stream)) {\n // Check for cancellation\n if (options.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n switch (event.type) {\n case 'stdout':\n case 'stderr':\n if (event.data) {\n // Update accumulated output\n if (event.type === 'stdout') stdout += event.data;\n if (event.type === 'stderr') stderr += event.data;\n\n // Call user's callback\n if (options.onOutput) {\n options.onOutput(event.type, event.data);\n }\n }\n break;\n\n case 'complete': {\n // Use result from complete event if available\n const duration = Date.now() - startTime;\n return {\n success: (event.exitCode ?? 0) === 0,\n exitCode: event.exitCode ?? 0,\n stdout,\n stderr,\n command,\n duration,\n timestamp,\n sessionId\n };\n }\n\n case 'error':\n throw new Error(event.data || 'Command execution failed');\n }\n }\n\n // If we get here without a complete event, something went wrong\n throw new Error('Stream ended without completion event');\n } catch (error) {\n if (options.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n throw error;\n }\n }\n\n private mapExecuteResponseToExecResult(\n response: ExecuteResponse,\n duration: number,\n sessionId?: string\n ): ExecResult {\n return {\n success: response.success,\n exitCode: response.exitCode,\n stdout: response.stdout,\n stderr: response.stderr,\n command: response.command,\n duration,\n timestamp: response.timestamp,\n sessionId\n };\n }\n\n /**\n * Create a Process domain object from HTTP client DTO\n * Centralizes process object creation with bound methods\n * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers\n */\n private createProcessFromDTO(\n data: {\n id: string;\n pid?: number;\n command: string;\n status: ProcessStatus;\n startTime: string | Date;\n endTime?: string | Date;\n exitCode?: number;\n },\n sessionId: string\n ): Process {\n return {\n id: data.id,\n pid: data.pid,\n command: data.command,\n status: data.status,\n startTime:\n typeof data.startTime === 'string'\n ? new Date(data.startTime)\n : data.startTime,\n endTime: data.endTime\n ? typeof data.endTime === 'string'\n ? new Date(data.endTime)\n : data.endTime\n : undefined,\n exitCode: data.exitCode,\n sessionId,\n\n kill: async (signal?: string) => {\n await this.killProcess(data.id, signal);\n },\n\n getStatus: async () => {\n const current = await this.getProcess(data.id);\n return current?.status || 'error';\n },\n\n getLogs: async () => {\n const logs = await this.getProcessLogs(data.id);\n return { stdout: logs.stdout, stderr: logs.stderr };\n }\n };\n }\n\n // Background process management\n async startProcess(\n command: string,\n options?: ProcessOptions,\n sessionId?: string\n ): Promise<Process> {\n // Use the new HttpClient method to start the process\n try {\n const session = sessionId ?? (await this.ensureDefaultSession());\n const requestOptions = {\n ...(options?.processId !== undefined && {\n processId: options.processId\n }),\n ...(options?.timeout !== undefined && { timeoutMs: options.timeout }),\n ...(options?.env !== undefined && { env: options.env }),\n ...(options?.cwd !== undefined && { cwd: options.cwd }),\n ...(options?.encoding !== undefined && { encoding: options.encoding }),\n ...(options?.autoCleanup !== undefined && {\n autoCleanup: options.autoCleanup\n })\n };\n\n const response = await this.client.processes.startProcess(\n command,\n session,\n requestOptions\n );\n\n const processObj = this.createProcessFromDTO(\n {\n id: response.processId,\n pid: response.pid,\n command: response.command,\n status: 'running' as ProcessStatus,\n startTime: new Date(),\n endTime: undefined,\n exitCode: undefined\n },\n session\n );\n\n // Call onStart callback if provided\n if (options?.onStart) {\n options.onStart(processObj);\n }\n\n return processObj;\n } catch (error) {\n if (options?.onError && error instanceof Error) {\n options.onError(error);\n }\n\n throw error;\n }\n }\n\n async listProcesses(sessionId?: string): Promise<Process[]> {\n const session = sessionId ?? (await this.ensureDefaultSession());\n const response = await this.client.processes.listProcesses();\n\n return response.processes.map((processData) =>\n this.createProcessFromDTO(\n {\n id: processData.id,\n pid: processData.pid,\n command: processData.command,\n status: processData.status,\n startTime: processData.startTime,\n endTime: processData.endTime,\n exitCode: processData.exitCode\n },\n session\n )\n );\n }\n\n async getProcess(id: string, sessionId?: string): Promise<Process | null> {\n const session = sessionId ?? (await this.ensureDefaultSession());\n const response = await this.client.processes.getProcess(id);\n if (!response.process) {\n return null;\n }\n\n const processData = response.process;\n return this.createProcessFromDTO(\n {\n id: processData.id,\n pid: processData.pid,\n command: processData.command,\n status: processData.status,\n startTime: processData.startTime,\n endTime: processData.endTime,\n exitCode: processData.exitCode\n },\n session\n );\n }\n\n async killProcess(\n id: string,\n signal?: string,\n sessionId?: string\n ): Promise<void> {\n // Note: signal parameter is not currently supported by the HttpClient implementation\n // The HTTP client already throws properly typed errors, so we just let them propagate\n await this.client.processes.killProcess(id);\n }\n\n async killAllProcesses(sessionId?: string): Promise<number> {\n const response = await this.client.processes.killAllProcesses();\n return response.cleanedCount;\n }\n\n async cleanupCompletedProcesses(sessionId?: string): Promise<number> {\n // For now, this would need to be implemented as a container endpoint\n // as we no longer maintain local process storage\n // We'll return 0 as a placeholder until the container endpoint is added\n return 0;\n }\n\n async getProcessLogs(\n id: string,\n sessionId?: string\n ): Promise<{ stdout: string; stderr: string; processId: string }> {\n // The HTTP client already throws properly typed errors, so we just let them propagate\n const response = await this.client.processes.getProcessLogs(id);\n return {\n stdout: response.stdout,\n stderr: response.stderr,\n processId: response.processId\n };\n }\n\n // Streaming methods - return ReadableStream for RPC compatibility\n async execStream(\n command: string,\n options?: StreamOptions\n ): Promise<ReadableStream<Uint8Array>> {\n // Check for cancellation\n if (options?.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n const session = await this.ensureDefaultSession();\n // Get the stream from CommandClient\n return this.client.commands.executeStream(command, session, {\n timeoutMs: options?.timeout,\n env: options?.env,\n cwd: options?.cwd\n });\n }\n\n /**\n * Internal session-aware execStream implementation\n */\n private async execStreamWithSession(\n command: string,\n sessionId: string,\n options?: StreamOptions\n ): Promise<ReadableStream<Uint8Array>> {\n // Check for cancellation\n if (options?.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n return this.client.commands.executeStream(command, sessionId, {\n timeoutMs: options?.timeout,\n env: options?.env,\n cwd: options?.cwd\n });\n }\n\n /**\n * Stream logs from a background process as a ReadableStream.\n */\n async streamProcessLogs(\n processId: string,\n options?: { signal?: AbortSignal }\n ): Promise<ReadableStream<Uint8Array>> {\n // Check for cancellation\n if (options?.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n return this.client.processes.streamProcessLogs(processId);\n }\n\n async gitCheckout(\n repoUrl: string,\n options: { branch?: string; targetDir?: string; sessionId?: string }\n ) {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.git.checkout(repoUrl, session, {\n branch: options.branch,\n targetDir: options.targetDir\n });\n }\n\n async mkdir(\n path: string,\n options: { recursive?: boolean; sessionId?: string } = {}\n ) {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.mkdir(path, session, {\n recursive: options.recursive\n });\n }\n\n async writeFile(\n path: string,\n content: string,\n options: { encoding?: string; sessionId?: string } = {}\n ) {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.writeFile(path, content, session, {\n encoding: options.encoding\n });\n }\n\n async deleteFile(path: string, sessionId?: string) {\n const session = sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.deleteFile(path, session);\n }\n\n async renameFile(oldPath: string, newPath: string, sessionId?: string) {\n const session = sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.renameFile(oldPath, newPath, session);\n }\n\n async moveFile(\n sourcePath: string,\n destinationPath: string,\n sessionId?: string\n ) {\n const session = sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.moveFile(sourcePath, destinationPath, session);\n }\n\n async readFile(\n path: string,\n options: { encoding?: string; sessionId?: string } = {}\n ) {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.readFile(path, session, {\n encoding: options.encoding\n });\n }\n\n /**\n * Stream a file from the sandbox using Server-Sent Events\n * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities\n * @param path - Path to the file to stream\n * @param options - Optional session ID\n */\n async readFileStream(\n path: string,\n options: { sessionId?: string } = {}\n ): Promise<ReadableStream<Uint8Array>> {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.readFileStream(path, session);\n }\n\n async listFiles(\n path: string,\n options?: { recursive?: boolean; includeHidden?: boolean }\n ) {\n const session = await this.ensureDefaultSession();\n return this.client.files.listFiles(path, session, options);\n }\n\n async exists(path: string, sessionId?: string) {\n const session = sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.exists(path, session);\n }\n\n async exposePort(port: number, options: { name?: string; hostname: string }) {\n // Check if hostname is workers.dev domain (doesn't support wildcard subdomains)\n if (options.hostname.endsWith('.workers.dev')) {\n const errorResponse: ErrorResponse = {\n code: ErrorCode.CUSTOM_DOMAIN_REQUIRED,\n message: `Port exposure requires a custom domain. .workers.dev domains do not support wildcard subdomains required for port proxying.`,\n context: { originalError: options.hostname },\n httpStatus: 400,\n timestamp: new Date().toISOString()\n };\n throw new CustomDomainRequiredError(errorResponse);\n }\n\n const sessionId = await this.ensureDefaultSession();\n await this.client.ports.exposePort(port, sessionId, options?.name);\n\n // We need the sandbox name to construct preview URLs\n if (!this.sandboxName) {\n throw new Error(\n 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'\n );\n }\n\n // Generate and store token for this port\n const token = this.generatePortToken();\n this.portTokens.set(port, token);\n await this.persistPortTokens();\n\n const url = this.constructPreviewUrl(\n port,\n this.sandboxName,\n options.hostname,\n token\n );\n\n return {\n url,\n port,\n name: options?.name\n };\n }\n\n async unexposePort(port: number) {\n if (!validatePort(port)) {\n throw new SecurityError(\n `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`\n );\n }\n\n const sessionId = await this.ensureDefaultSession();\n await this.client.ports.unexposePort(port, sessionId);\n\n // Clean up token for this port\n if (this.portTokens.has(port)) {\n this.portTokens.delete(port);\n await this.persistPortTokens();\n }\n }\n\n async getExposedPorts(hostname: string) {\n const sessionId = await this.ensureDefaultSession();\n const response = await this.client.ports.getExposedPorts(sessionId);\n\n // We need the sandbox name to construct preview URLs\n if (!this.sandboxName) {\n throw new Error(\n 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'\n );\n }\n\n return response.ports.map((port) => {\n // Get token for this port - must exist for all exposed ports\n const token = this.portTokens.get(port.port);\n if (!token) {\n throw new Error(\n `Port ${port.port} is exposed but has no token. This should not happen.`\n );\n }\n\n return {\n url: this.constructPreviewUrl(\n port.port,\n this.sandboxName!,\n hostname,\n token\n ),\n port: port.port,\n status: port.status\n };\n });\n }\n\n async isPortExposed(port: number): Promise<boolean> {\n try {\n const sessionId = await this.ensureDefaultSession();\n const response = await this.client.ports.getExposedPorts(sessionId);\n return response.ports.some((exposedPort) => exposedPort.port === port);\n } catch (error) {\n this.logger.error(\n 'Error checking if port is exposed',\n error instanceof Error ? error : new Error(String(error)),\n { port }\n );\n return false;\n }\n }\n\n async validatePortToken(port: number, token: string): Promise<boolean> {\n // First check if port is exposed\n const isExposed = await this.isPortExposed(port);\n if (!isExposed) {\n return false;\n }\n\n // Get stored token for this port - must exist for all exposed ports\n const storedToken = this.portTokens.get(port);\n if (!storedToken) {\n // This should not happen - all exposed ports must have tokens\n this.logger.error(\n 'Port is exposed but has no token - bug detected',\n undefined,\n { port }\n );\n return false;\n }\n\n // Constant-time comparison to prevent timing attacks\n return storedToken === token;\n }\n\n private generatePortToken(): string {\n // Generate cryptographically secure 16-character token using Web Crypto API\n // Available in Cloudflare Workers runtime\n const array = new Uint8Array(12); // 12 bytes = 16 base64url chars (after padding removal)\n crypto.getRandomValues(array);\n\n // Convert to base64url format (URL-safe, no padding, lowercase)\n const base64 = btoa(String.fromCharCode(...array));\n return base64\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '')\n .toLowerCase();\n }\n\n private async persistPortTokens(): Promise<void> {\n // Convert Map to plain object for storage\n const tokensObj: Record<string, string> = {};\n for (const [port, token] of this.portTokens.entries()) {\n tokensObj[port.toString()] = token;\n }\n await this.ctx.storage.put('portTokens', tokensObj);\n }\n\n private constructPreviewUrl(\n port: number,\n sandboxId: string,\n hostname: string,\n token: string\n ): string {\n if (!validatePort(port)) {\n throw new SecurityError(\n `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`\n );\n }\n\n // Hostnames are case-insensitive, routing requests to wrong DO instance when keys contain uppercase letters\n const effectiveId = this.sandboxName || sandboxId;\n const hasUppercase = /[A-Z]/.test(effectiveId);\n if (!this.normalizeId && hasUppercase) {\n throw new SecurityError(\n `Preview URLs require lowercase sandbox IDs. Your ID \"${effectiveId}\" contains uppercase letters.\\n\\n` +\n `To fix this:\\n` +\n `1. Create a new sandbox with: getSandbox(ns, \"${effectiveId}\", { normalizeId: true })\\n` +\n `2. This will create a sandbox with ID: \"${effectiveId.toLowerCase()}\"\\n\\n` +\n `Note: Due to DNS case-insensitivity, IDs with uppercase letters cannot be used with preview URLs.`\n );\n }\n\n const sanitizedSandboxId = sanitizeSandboxId(sandboxId).toLowerCase();\n\n const isLocalhost = isLocalhostPattern(hostname);\n\n if (isLocalhost) {\n const [host, portStr] = hostname.split(':');\n const mainPort = portStr || '80';\n\n try {\n const baseUrl = new URL(`http://${host}:${mainPort}`);\n const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;\n baseUrl.hostname = subdomainHost;\n\n return baseUrl.toString();\n } catch (error) {\n throw new SecurityError(\n `Failed to construct preview URL: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\n }\n }\n\n try {\n const baseUrl = new URL(`https://${hostname}`);\n const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;\n baseUrl.hostname = subdomainHost;\n\n return baseUrl.toString();\n } catch (error) {\n throw new SecurityError(\n `Failed to construct preview URL: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\n }\n }\n\n // ============================================================================\n // Session Management - Advanced Use Cases\n // ============================================================================\n\n /**\n * Create isolated execution session for advanced use cases\n * Returns ExecutionSession with full sandbox API bound to specific session\n */\n async createSession(options?: SessionOptions): Promise<ExecutionSession> {\n const sessionId = options?.id || `session-${Date.now()}`;\n\n const mergedEnv = {\n ...this.envVars,\n ...(options?.env ?? {})\n };\n const envPayload =\n Object.keys(mergedEnv).length > 0 ? mergedEnv : undefined;\n\n // Create session in container\n await this.client.utils.createSession({\n id: sessionId,\n ...(envPayload && { env: envPayload }),\n ...(options?.cwd && { cwd: options.cwd })\n });\n\n // Return wrapper that binds sessionId to all operations\n return this.getSessionWrapper(sessionId);\n }\n\n /**\n * Get an existing session by ID\n * Returns ExecutionSession wrapper bound to the specified session\n *\n * This is useful for retrieving sessions across different requests/contexts\n * without storing the ExecutionSession object (which has RPC lifecycle limitations)\n *\n * @param sessionId - The ID of an existing session\n * @returns ExecutionSession wrapper bound to the session\n */\n async getSession(sessionId: string): Promise<ExecutionSession> {\n // No need to verify session exists in container - operations will fail naturally if it doesn't\n return this.getSessionWrapper(sessionId);\n }\n\n /**\n * Delete an execution session\n * Cleans up session resources and removes it from the container\n * Note: Cannot delete the default session. To reset the default session,\n * use sandbox.destroy() to terminate the entire sandbox.\n *\n * @param sessionId - The ID of the session to delete\n * @returns Result with success status, sessionId, and timestamp\n * @throws Error if attempting to delete the default session\n */\n async deleteSession(sessionId: string): Promise<SessionDeleteResult> {\n // Prevent deletion of default session\n if (this.defaultSession && sessionId === this.defaultSession) {\n throw new Error(\n `Cannot delete default session '${sessionId}'. Use sandbox.destroy() to terminate the sandbox.`\n );\n }\n\n const response = await this.client.utils.deleteSession(sessionId);\n\n // Map HTTP response to result type\n return {\n success: response.success,\n sessionId: response.sessionId,\n timestamp: response.timestamp\n };\n }\n\n /**\n * Internal helper to create ExecutionSession wrapper for a given sessionId\n * Used by both createSession and getSession\n */\n private getSessionWrapper(sessionId: string): ExecutionSession {\n return {\n id: sessionId,\n\n // Command execution - delegate to internal session-aware methods\n exec: (command, options) =>\n this.execWithSession(command, sessionId, options),\n execStream: (command, options) =>\n this.execStreamWithSession(command, sessionId, options),\n\n // Process management\n startProcess: (command, options) =>\n this.startProcess(command, options, sessionId),\n listProcesses: () => this.listProcesses(sessionId),\n getProcess: (id) => this.getProcess(id, sessionId),\n killProcess: (id, signal) => this.killProcess(id, signal),\n killAllProcesses: () => this.killAllProcesses(),\n cleanupCompletedProcesses: () => this.cleanupCompletedProcesses(),\n getProcessLogs: (id) => this.getProcessLogs(id),\n streamProcessLogs: (processId, options) =>\n this.streamProcessLogs(processId, options),\n\n // File operations - pass sessionId via options or parameter\n writeFile: (path, content, options) =>\n this.writeFile(path, content, { ...options, sessionId }),\n readFile: (path, options) =>\n this.readFile(path, { ...options, sessionId }),\n readFileStream: (path) => this.readFileStream(path, { sessionId }),\n mkdir: (path, options) => this.mkdir(path, { ...options, sessionId }),\n deleteFile: (path) => this.deleteFile(path, sessionId),\n renameFile: (oldPath, newPath) =>\n this.renameFile(oldPath, newPath, sessionId),\n moveFile: (sourcePath, destPath) =>\n this.moveFile(sourcePath, destPath, sessionId),\n listFiles: (path, options) =>\n this.client.files.listFiles(path, sessionId, options),\n exists: (path) => this.exists(path, sessionId),\n\n // Git operations\n gitCheckout: (repoUrl, options) =>\n this.gitCheckout(repoUrl, { ...options, sessionId }),\n\n // Environment management - needs special handling\n setEnvVars: async (envVars: Record<string, string>) => {\n try {\n // Set environment variables by executing export commands\n for (const [key, value] of Object.entries(envVars)) {\n const escapedValue = value.replace(/'/g, \"'\\\\''\");\n const exportCommand = `export ${key}='${escapedValue}'`;\n\n const result = await this.client.commands.execute(\n exportCommand,\n sessionId\n );\n\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to set ${key}: ${result.stderr || 'Unknown error'}`\n );\n }\n }\n } catch (error) {\n this.logger.error(\n 'Failed to set environment variables',\n error instanceof Error ? error : new Error(String(error)),\n { sessionId }\n );\n throw error;\n }\n },\n\n // Code interpreter methods - delegate to sandbox's code interpreter\n createCodeContext: (options) =>\n this.codeInterpreter.createCodeContext(options),\n runCode: async (code, options) => {\n const execution = await this.codeInterpreter.runCode(code, options);\n return execution.toJSON();\n },\n runCodeStream: (code, options) =>\n this.codeInterpreter.runCodeStream(code, options),\n listCodeContexts: () => this.codeInterpreter.listCodeContexts(),\n deleteCodeContext: (contextId) =>\n this.codeInterpreter.deleteCodeContext(contextId),\n\n // Bucket mounting - sandbox-level operations\n mountBucket: (bucket, mountPath, options) =>\n this.mountBucket(bucket, mountPath, options),\n unmountBucket: (mountPath) => this.unmountBucket(mountPath)\n };\n }\n\n // ============================================================================\n // Code interpreter methods - delegate to CodeInterpreter wrapper\n // ============================================================================\n\n async createCodeContext(\n options?: CreateContextOptions\n ): Promise<CodeContext> {\n return this.codeInterpreter.createCodeContext(options);\n }\n\n async runCode(\n code: string,\n options?: RunCodeOptions\n ): Promise<ExecutionResult> {\n const execution = await this.codeInterpreter.runCode(code, options);\n return execution.toJSON();\n }\n\n async runCodeStream(\n code: string,\n options?: RunCodeOptions\n ): Promise<ReadableStream> {\n return this.codeInterpreter.runCodeStream(code, options);\n }\n\n async listCodeContexts(): Promise<CodeContext[]> {\n return this.codeInterpreter.listCodeContexts();\n }\n\n async deleteCodeContext(contextId: string): Promise<void> {\n return this.codeInterpreter.deleteCodeContext(contextId);\n }\n}\n","import type { FileChunk, FileMetadata, FileStreamEvent } from '@repo/shared';\n\n/**\n * Parse SSE (Server-Sent Events) lines from a stream\n */\nasync function* parseSSE(\n stream: ReadableStream<Uint8Array>\n): AsyncGenerator<FileStreamEvent> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n\n // Keep the last incomplete line in the buffer\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6); // Remove 'data: ' prefix\n try {\n const event = JSON.parse(data) as FileStreamEvent;\n yield event;\n } catch {\n // Skip invalid JSON events and continue processing\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Stream a file from the sandbox with automatic base64 decoding for binary files\n *\n * @param stream - The ReadableStream from readFileStream()\n * @returns AsyncGenerator that yields FileChunk (string for text, Uint8Array for binary)\n *\n * @example\n * ```ts\n * const stream = await sandbox.readFileStream('/path/to/file.png');\n * for await (const chunk of streamFile(stream)) {\n * if (chunk instanceof Uint8Array) {\n * // Binary chunk\n * console.log('Binary chunk:', chunk.length, 'bytes');\n * } else {\n * // Text chunk\n * console.log('Text chunk:', chunk);\n * }\n * }\n * ```\n */\nexport async function* streamFile(\n stream: ReadableStream<Uint8Array>\n): AsyncGenerator<FileChunk, FileMetadata> {\n let metadata: FileMetadata | null = null;\n\n for await (const event of parseSSE(stream)) {\n switch (event.type) {\n case 'metadata':\n metadata = {\n mimeType: event.mimeType,\n size: event.size,\n isBinary: event.isBinary,\n encoding: event.encoding\n };\n break;\n\n case 'chunk':\n if (!metadata) {\n throw new Error('Received chunk before metadata');\n }\n\n if (metadata.isBinary && metadata.encoding === 'base64') {\n // Decode base64 to Uint8Array for binary files\n const binaryString = atob(event.data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n yield bytes;\n } else {\n // Text files - yield as-is\n yield event.data;\n }\n break;\n\n case 'complete':\n if (!metadata) {\n throw new Error('Stream completed without metadata');\n }\n return metadata;\n\n case 'error':\n throw new Error(`File streaming error: ${event.error}`);\n }\n }\n\n throw new Error('Stream ended unexpectedly');\n}\n\n/**\n * Collect an entire file into memory from a stream\n *\n * @param stream - The ReadableStream from readFileStream()\n * @returns Object containing the file content and metadata\n *\n * @example\n * ```ts\n * const stream = await sandbox.readFileStream('/path/to/file.txt');\n * const { content, metadata } = await collectFile(stream);\n * console.log('Content:', content);\n * console.log('MIME type:', metadata.mimeType);\n * ```\n */\nexport async function collectFile(stream: ReadableStream<Uint8Array>): Promise<{\n content: string | Uint8Array;\n metadata: FileMetadata;\n}> {\n const chunks: Array<string | Uint8Array> = [];\n\n // Iterate through the generator and get the return value (metadata)\n const generator = streamFile(stream);\n let result = await generator.next();\n\n while (!result.done) {\n chunks.push(result.value);\n result = await generator.next();\n }\n\n const metadata = result.value;\n\n if (!metadata) {\n throw new Error('Failed to get file metadata');\n }\n\n // Combine chunks based on type\n if (metadata.isBinary) {\n // Binary file - combine Uint8Arrays\n const totalLength = chunks.reduce(\n (sum, chunk) => sum + (chunk instanceof Uint8Array ? chunk.length : 0),\n 0\n );\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n if (chunk instanceof Uint8Array) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n }\n return { content: combined, metadata };\n } else {\n // Text file - combine strings\n const combined = chunks.filter((c) => typeof c === 'string').join('');\n return { content: combined, metadata };\n }\n}\n"],"mappings":";;;;;;;;AAIA,MAAa,YAAY;CAErB,gBAAgB;CAEhB,mBAAmB;CAEnB,aAAa;CAEb,cAAc;CACd,eAAe;CAEf,UAAU;CACV,gBAAgB;CAChB,eAAe;CACf,WAAW;CACX,eAAe;CACf,gBAAgB;CAChB,kBAAkB;CAElB,mBAAmB;CAEnB,2BAA2B;CAC3B,iBAAiB;CAEjB,yBAAyB;CACzB,oBAAoB;CAEpB,mBAAmB;CAEnB,2BAA2B;CAC3B,eAAe;CAEf,sBAAsB;CACtB,aAAa;CAEb,kBAAkB;CAElB,qBAAqB;CACrB,cAAc;CAEd,wBAAwB;CACxB,sBAAsB;CAEtB,wBAAwB;CAExB,0BAA0B;CAC1B,sBAAsB;CAEtB,iBAAiB;CAEjB,mBAAmB;CAEnB,iBAAiB;CAEjB,kBAAkB;CAClB,qBAAqB;CACrB,sBAA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iBAAiB,YAAY;AAC/B,YAAS,IAAI,OAAO,OAAO;AAC3B,aAAU,MAAM;;AAGpB,SAAO;GAAE,SAAS;GAAU;GAAU;OAItC,QAAO;EAAE,SADQ,OAAO,QAAQ,MAAM,OAAO,MAAM,SAAS,CAAC,KAAK,GAAG;EACzC;EAAU"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["errorResponse: ErrorResponse<TContext>","errorData: NewErrorResponse","data: ExecuteRequest","data: GitCheckoutRequest","lastError: Error | undefined","data: StartProcessRequest","clientOptions: HttpClientOptions","code?: string","proxyUrl: string","sanitizedSandboxId: string","provider: BucketProvider | null","s3fsArgs: string[]","request: Request","port: number | undefined","error: unknown","result: ExecResult","tokensObj: Record<string, string>","metadata: FileMetadata | null","chunks: Array<string | Uint8Array>"],"sources":["../../shared/dist/errors/codes.js","../../shared/dist/errors/status-map.js","../src/errors/classes.ts","../src/errors/adapter.ts","../src/clients/base-client.ts","../src/clients/command-client.ts","../src/clients/file-client.ts","../src/clients/git-client.ts","../src/clients/interpreter-client.ts","../src/clients/port-client.ts","../src/clients/process-client.ts","../src/clients/utility-client.ts","../src/clients/sandbox-client.ts","../src/security.ts","../src/interpreter.ts","../src/request-handler.ts","../src/sse-parser.ts","../src/storage-mount/errors.ts","../src/storage-mount/credential-detection.ts","../src/storage-mount/provider-detection.ts","../src/version.ts","../src/sandbox.ts","../src/file-stream.ts"],"sourcesContent":["/**\n * Centralized error code registry\n * Each code maps to a specific error type with consistent semantics\n */\nexport const ErrorCode = {\n // File System Errors (404)\n FILE_NOT_FOUND: 'FILE_NOT_FOUND',\n // Permission Errors (403)\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n // File System Errors (409)\n FILE_EXISTS: 'FILE_EXISTS',\n // File System Errors (400)\n IS_DIRECTORY: 'IS_DIRECTORY',\n NOT_DIRECTORY: 'NOT_DIRECTORY',\n // File System Errors (500)\n NO_SPACE: 'NO_SPACE',\n TOO_MANY_FILES: 'TOO_MANY_FILES',\n RESOURCE_BUSY: 'RESOURCE_BUSY',\n READ_ONLY: 'READ_ONLY',\n NAME_TOO_LONG: 'NAME_TOO_LONG',\n TOO_MANY_LINKS: 'TOO_MANY_LINKS',\n FILESYSTEM_ERROR: 'FILESYSTEM_ERROR',\n // Command Errors (404)\n COMMAND_NOT_FOUND: 'COMMAND_NOT_FOUND',\n // Command Errors (403/400)\n COMMAND_PERMISSION_DENIED: 'COMMAND_PERMISSION_DENIED',\n INVALID_COMMAND: 'INVALID_COMMAND',\n // Command Errors (500)\n COMMAND_EXECUTION_ERROR: 'COMMAND_EXECUTION_ERROR',\n STREAM_START_ERROR: 'STREAM_START_ERROR',\n // Process Errors (404)\n PROCESS_NOT_FOUND: 'PROCESS_NOT_FOUND',\n // Process Errors (403/500)\n PROCESS_PERMISSION_DENIED: 'PROCESS_PERMISSION_DENIED',\n PROCESS_ERROR: 'PROCESS_ERROR',\n // Port Errors (409)\n PORT_ALREADY_EXPOSED: 'PORT_ALREADY_EXPOSED',\n PORT_IN_USE: 'PORT_IN_USE',\n // Port Errors (404)\n PORT_NOT_EXPOSED: 'PORT_NOT_EXPOSED',\n // Port Errors (400)\n INVALID_PORT_NUMBER: 'INVALID_PORT_NUMBER',\n INVALID_PORT: 'INVALID_PORT',\n // Port Errors (502/500)\n SERVICE_NOT_RESPONDING: 'SERVICE_NOT_RESPONDING',\n PORT_OPERATION_ERROR: 'PORT_OPERATION_ERROR',\n // Port Errors (400)\n CUSTOM_DOMAIN_REQUIRED: 'CUSTOM_DOMAIN_REQUIRED',\n // Git Errors (404)\n GIT_REPOSITORY_NOT_FOUND: 'GIT_REPOSITORY_NOT_FOUND',\n GIT_BRANCH_NOT_FOUND: 'GIT_BRANCH_NOT_FOUND',\n // Git Errors (401)\n GIT_AUTH_FAILED: 'GIT_AUTH_FAILED',\n // Git Errors (502)\n GIT_NETWORK_ERROR: 'GIT_NETWORK_ERROR',\n // Git Errors (400)\n INVALID_GIT_URL: 'INVALID_GIT_URL',\n // Git Errors (500)\n GIT_CLONE_FAILED: 'GIT_CLONE_FAILED',\n GIT_CHECKOUT_FAILED: 'GIT_CHECKOUT_FAILED',\n GIT_OPERATION_FAILED: 'GIT_OPERATION_FAILED',\n // Bucket mounting errors\n BUCKET_MOUNT_ERROR: 'BUCKET_MOUNT_ERROR',\n S3FS_MOUNT_ERROR: 'S3FS_MOUNT_ERROR',\n MISSING_CREDENTIALS: 'MISSING_CREDENTIALS',\n INVALID_MOUNT_CONFIG: 'INVALID_MOUNT_CONFIG',\n // Code Interpreter Errors (503)\n INTERPRETER_NOT_READY: 'INTERPRETER_NOT_READY',\n // Code Interpreter Errors (404)\n CONTEXT_NOT_FOUND: 'CONTEXT_NOT_FOUND',\n // Code Interpreter Errors (500)\n CODE_EXECUTION_ERROR: 'CODE_EXECUTION_ERROR',\n // Validation Errors (400)\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n // Generic Errors (400/500)\n INVALID_JSON_RESPONSE: 'INVALID_JSON_RESPONSE',\n UNKNOWN_ERROR: 'UNKNOWN_ERROR',\n INTERNAL_ERROR: 'INTERNAL_ERROR'\n};\n","import { ErrorCode } from './codes';\n/**\n * Maps error codes to HTTP status codes\n * Centralized mapping ensures consistency across SDK\n */\nexport const ERROR_STATUS_MAP = {\n // 404 Not Found\n [ErrorCode.FILE_NOT_FOUND]: 404,\n [ErrorCode.COMMAND_NOT_FOUND]: 404,\n [ErrorCode.PROCESS_NOT_FOUND]: 404,\n [ErrorCode.PORT_NOT_EXPOSED]: 404,\n [ErrorCode.GIT_REPOSITORY_NOT_FOUND]: 404,\n [ErrorCode.GIT_BRANCH_NOT_FOUND]: 404,\n [ErrorCode.CONTEXT_NOT_FOUND]: 404,\n // 400 Bad Request\n [ErrorCode.IS_DIRECTORY]: 400,\n [ErrorCode.NOT_DIRECTORY]: 400,\n [ErrorCode.INVALID_COMMAND]: 400,\n [ErrorCode.INVALID_PORT_NUMBER]: 400,\n [ErrorCode.INVALID_PORT]: 400,\n [ErrorCode.INVALID_GIT_URL]: 400,\n [ErrorCode.CUSTOM_DOMAIN_REQUIRED]: 400,\n [ErrorCode.INVALID_JSON_RESPONSE]: 400,\n [ErrorCode.NAME_TOO_LONG]: 400,\n [ErrorCode.VALIDATION_FAILED]: 400,\n [ErrorCode.MISSING_CREDENTIALS]: 400,\n [ErrorCode.INVALID_MOUNT_CONFIG]: 400,\n // 401 Unauthorized\n [ErrorCode.GIT_AUTH_FAILED]: 401,\n // 403 Forbidden\n [ErrorCode.PERMISSION_DENIED]: 403,\n [ErrorCode.COMMAND_PERMISSION_DENIED]: 403,\n [ErrorCode.PROCESS_PERMISSION_DENIED]: 403,\n [ErrorCode.READ_ONLY]: 403,\n // 409 Conflict\n [ErrorCode.FILE_EXISTS]: 409,\n [ErrorCode.PORT_ALREADY_EXPOSED]: 409,\n [ErrorCode.PORT_IN_USE]: 409,\n [ErrorCode.RESOURCE_BUSY]: 409,\n // 502 Bad Gateway\n [ErrorCode.SERVICE_NOT_RESPONDING]: 502,\n [ErrorCode.GIT_NETWORK_ERROR]: 502,\n // 503 Service Unavailable\n [ErrorCode.INTERPRETER_NOT_READY]: 503,\n // 500 Internal Server Error\n [ErrorCode.NO_SPACE]: 500,\n [ErrorCode.TOO_MANY_FILES]: 500,\n [ErrorCode.TOO_MANY_LINKS]: 500,\n [ErrorCode.FILESYSTEM_ERROR]: 500,\n [ErrorCode.COMMAND_EXECUTION_ERROR]: 500,\n [ErrorCode.STREAM_START_ERROR]: 500,\n [ErrorCode.PROCESS_ERROR]: 500,\n [ErrorCode.PORT_OPERATION_ERROR]: 500,\n [ErrorCode.GIT_CLONE_FAILED]: 500,\n [ErrorCode.GIT_CHECKOUT_FAILED]: 500,\n [ErrorCode.GIT_OPERATION_FAILED]: 500,\n [ErrorCode.CODE_EXECUTION_ERROR]: 500,\n [ErrorCode.BUCKET_MOUNT_ERROR]: 500,\n [ErrorCode.S3FS_MOUNT_ERROR]: 500,\n [ErrorCode.UNKNOWN_ERROR]: 500,\n [ErrorCode.INTERNAL_ERROR]: 500\n};\n/**\n * Get HTTP status code for an error code\n * Falls back to 500 for unknown errors\n */\nexport function getHttpStatus(code) {\n return ERROR_STATUS_MAP[code] || 500;\n}\n","/**\n * Type-safe error classes that wrap ErrorResponse from container\n *\n * All error classes extend SandboxError<TContext> which wraps the full ErrorResponse\n * and provides type-safe accessors for error properties.\n */\n\nimport type {\n CodeExecutionContext,\n CommandErrorContext,\n CommandNotFoundContext,\n ContextNotFoundContext,\n ErrorResponse,\n FileExistsContext,\n FileNotFoundContext,\n FileSystemContext,\n GitAuthFailedContext,\n GitBranchNotFoundContext,\n GitErrorContext,\n GitRepositoryNotFoundContext,\n InternalErrorContext,\n InterpreterNotReadyContext,\n InvalidPortContext,\n PortAlreadyExposedContext,\n PortErrorContext,\n PortNotExposedContext,\n ProcessErrorContext,\n ProcessNotFoundContext,\n ValidationFailedContext\n} from '@repo/shared/errors';\n\n/**\n * Base SDK error that wraps ErrorResponse\n * Preserves all error information from container\n */\nexport class SandboxError<TContext = Record<string, unknown>> extends Error {\n constructor(public readonly errorResponse: ErrorResponse<TContext>) {\n super(errorResponse.message);\n this.name = 'SandboxError';\n }\n\n // Convenience accessors\n get code() {\n return this.errorResponse.code;\n }\n get context() {\n return this.errorResponse.context;\n }\n get httpStatus() {\n return this.errorResponse.httpStatus;\n }\n get operation() {\n return this.errorResponse.operation;\n }\n get suggestion() {\n return this.errorResponse.suggestion;\n }\n get timestamp() {\n return this.errorResponse.timestamp;\n }\n get documentation() {\n return this.errorResponse.documentation;\n }\n\n // Custom serialization for logging\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n context: this.context,\n httpStatus: this.httpStatus,\n operation: this.operation,\n suggestion: this.suggestion,\n timestamp: this.timestamp,\n documentation: this.documentation,\n stack: this.stack\n };\n }\n}\n\n// ============================================================================\n// File System Errors\n// ============================================================================\n\n/**\n * Error thrown when a file or directory is not found\n */\nexport class FileNotFoundError extends SandboxError<FileNotFoundContext> {\n constructor(errorResponse: ErrorResponse<FileNotFoundContext>) {\n super(errorResponse);\n this.name = 'FileNotFoundError';\n }\n\n // Type-safe accessors\n get path() {\n return this.context.path;\n }\n}\n\n/**\n * Error thrown when a file already exists\n */\nexport class FileExistsError extends SandboxError<FileExistsContext> {\n constructor(errorResponse: ErrorResponse<FileExistsContext>) {\n super(errorResponse);\n this.name = 'FileExistsError';\n }\n\n // Type-safe accessor\n get path() {\n return this.context.path;\n }\n}\n\n/**\n * Generic file system error (permissions, disk full, etc.)\n */\nexport class FileSystemError extends SandboxError<FileSystemContext> {\n constructor(errorResponse: ErrorResponse<FileSystemContext>) {\n super(errorResponse);\n this.name = 'FileSystemError';\n }\n\n // Type-safe accessors\n get path() {\n return this.context.path;\n }\n get stderr() {\n return this.context.stderr;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n}\n\n/**\n * Error thrown when permission is denied\n */\nexport class PermissionDeniedError extends SandboxError<FileSystemContext> {\n constructor(errorResponse: ErrorResponse<FileSystemContext>) {\n super(errorResponse);\n this.name = 'PermissionDeniedError';\n }\n\n get path() {\n return this.context.path;\n }\n}\n\n// ============================================================================\n// Command Errors\n// ============================================================================\n\n/**\n * Error thrown when a command is not found\n */\nexport class CommandNotFoundError extends SandboxError<CommandNotFoundContext> {\n constructor(errorResponse: ErrorResponse<CommandNotFoundContext>) {\n super(errorResponse);\n this.name = 'CommandNotFoundError';\n }\n\n // Type-safe accessor\n get command() {\n return this.context.command;\n }\n}\n\n/**\n * Generic command execution error\n */\nexport class CommandError extends SandboxError<CommandErrorContext> {\n constructor(errorResponse: ErrorResponse<CommandErrorContext>) {\n super(errorResponse);\n this.name = 'CommandError';\n }\n\n // Type-safe accessors\n get command() {\n return this.context.command;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n get stdout() {\n return this.context.stdout;\n }\n get stderr() {\n return this.context.stderr;\n }\n}\n\n// ============================================================================\n// Process Errors\n// ============================================================================\n\n/**\n * Error thrown when a process is not found\n */\nexport class ProcessNotFoundError extends SandboxError<ProcessNotFoundContext> {\n constructor(errorResponse: ErrorResponse<ProcessNotFoundContext>) {\n super(errorResponse);\n this.name = 'ProcessNotFoundError';\n }\n\n // Type-safe accessor\n get processId() {\n return this.context.processId;\n }\n}\n\n/**\n * Generic process error\n */\nexport class ProcessError extends SandboxError<ProcessErrorContext> {\n constructor(errorResponse: ErrorResponse<ProcessErrorContext>) {\n super(errorResponse);\n this.name = 'ProcessError';\n }\n\n // Type-safe accessors\n get processId() {\n return this.context.processId;\n }\n get pid() {\n return this.context.pid;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n get stderr() {\n return this.context.stderr;\n }\n}\n\n// ============================================================================\n// Port Errors\n// ============================================================================\n\n/**\n * Error thrown when a port is already exposed\n */\nexport class PortAlreadyExposedError extends SandboxError<PortAlreadyExposedContext> {\n constructor(errorResponse: ErrorResponse<PortAlreadyExposedContext>) {\n super(errorResponse);\n this.name = 'PortAlreadyExposedError';\n }\n\n // Type-safe accessors\n get port() {\n return this.context.port;\n }\n get portName() {\n return this.context.portName;\n }\n}\n\n/**\n * Error thrown when a port is not exposed\n */\nexport class PortNotExposedError extends SandboxError<PortNotExposedContext> {\n constructor(errorResponse: ErrorResponse<PortNotExposedContext>) {\n super(errorResponse);\n this.name = 'PortNotExposedError';\n }\n\n // Type-safe accessor\n get port() {\n return this.context.port;\n }\n}\n\n/**\n * Error thrown when a port number is invalid\n */\nexport class InvalidPortError extends SandboxError<InvalidPortContext> {\n constructor(errorResponse: ErrorResponse<InvalidPortContext>) {\n super(errorResponse);\n this.name = 'InvalidPortError';\n }\n\n // Type-safe accessors\n get port() {\n return this.context.port;\n }\n get reason() {\n return this.context.reason;\n }\n}\n\n/**\n * Error thrown when a service on a port is not responding\n */\nexport class ServiceNotRespondingError extends SandboxError<PortErrorContext> {\n constructor(errorResponse: ErrorResponse<PortErrorContext>) {\n super(errorResponse);\n this.name = 'ServiceNotRespondingError';\n }\n\n // Type-safe accessors\n get port() {\n return this.context.port;\n }\n get portName() {\n return this.context.portName;\n }\n}\n\n/**\n * Error thrown when a port is already in use\n */\nexport class PortInUseError extends SandboxError<PortErrorContext> {\n constructor(errorResponse: ErrorResponse<PortErrorContext>) {\n super(errorResponse);\n this.name = 'PortInUseError';\n }\n\n // Type-safe accessor\n get port() {\n return this.context.port;\n }\n}\n\n/**\n * Generic port operation error\n */\nexport class PortError extends SandboxError<PortErrorContext> {\n constructor(errorResponse: ErrorResponse<PortErrorContext>) {\n super(errorResponse);\n this.name = 'PortError';\n }\n\n // Type-safe accessors\n get port() {\n return this.context.port;\n }\n get portName() {\n return this.context.portName;\n }\n get stderr() {\n return this.context.stderr;\n }\n}\n\n/**\n * Error thrown when port exposure requires a custom domain\n */\nexport class CustomDomainRequiredError extends SandboxError<InternalErrorContext> {\n constructor(errorResponse: ErrorResponse<InternalErrorContext>) {\n super(errorResponse);\n this.name = 'CustomDomainRequiredError';\n }\n}\n\n// ============================================================================\n// Git Errors\n// ============================================================================\n\n/**\n * Error thrown when a git repository is not found\n */\nexport class GitRepositoryNotFoundError extends SandboxError<GitRepositoryNotFoundContext> {\n constructor(errorResponse: ErrorResponse<GitRepositoryNotFoundContext>) {\n super(errorResponse);\n this.name = 'GitRepositoryNotFoundError';\n }\n\n // Type-safe accessor\n get repository() {\n return this.context.repository;\n }\n}\n\n/**\n * Error thrown when git authentication fails\n */\nexport class GitAuthenticationError extends SandboxError<GitAuthFailedContext> {\n constructor(errorResponse: ErrorResponse<GitAuthFailedContext>) {\n super(errorResponse);\n this.name = 'GitAuthenticationError';\n }\n\n // Type-safe accessor\n get repository() {\n return this.context.repository;\n }\n}\n\n/**\n * Error thrown when a git branch is not found\n */\nexport class GitBranchNotFoundError extends SandboxError<GitBranchNotFoundContext> {\n constructor(errorResponse: ErrorResponse<GitBranchNotFoundContext>) {\n super(errorResponse);\n this.name = 'GitBranchNotFoundError';\n }\n\n // Type-safe accessors\n get branch() {\n return this.context.branch;\n }\n get repository() {\n return this.context.repository;\n }\n}\n\n/**\n * Error thrown when a git network operation fails\n */\nexport class GitNetworkError extends SandboxError<GitErrorContext> {\n constructor(errorResponse: ErrorResponse<GitErrorContext>) {\n super(errorResponse);\n this.name = 'GitNetworkError';\n }\n\n // Type-safe accessors\n get repository() {\n return this.context.repository;\n }\n get branch() {\n return this.context.branch;\n }\n get targetDir() {\n return this.context.targetDir;\n }\n}\n\n/**\n * Error thrown when git clone fails\n */\nexport class GitCloneError extends SandboxError<GitErrorContext> {\n constructor(errorResponse: ErrorResponse<GitErrorContext>) {\n super(errorResponse);\n this.name = 'GitCloneError';\n }\n\n // Type-safe accessors\n get repository() {\n return this.context.repository;\n }\n get targetDir() {\n return this.context.targetDir;\n }\n get stderr() {\n return this.context.stderr;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n}\n\n/**\n * Error thrown when git checkout fails\n */\nexport class GitCheckoutError extends SandboxError<GitErrorContext> {\n constructor(errorResponse: ErrorResponse<GitErrorContext>) {\n super(errorResponse);\n this.name = 'GitCheckoutError';\n }\n\n // Type-safe accessors\n get branch() {\n return this.context.branch;\n }\n get repository() {\n return this.context.repository;\n }\n get stderr() {\n return this.context.stderr;\n }\n}\n\n/**\n * Error thrown when a git URL is invalid\n */\nexport class InvalidGitUrlError extends SandboxError<ValidationFailedContext> {\n constructor(errorResponse: ErrorResponse<ValidationFailedContext>) {\n super(errorResponse);\n this.name = 'InvalidGitUrlError';\n }\n\n // Type-safe accessor\n get validationErrors() {\n return this.context.validationErrors;\n }\n}\n\n/**\n * Generic git operation error\n */\nexport class GitError extends SandboxError<GitErrorContext> {\n constructor(errorResponse: ErrorResponse<GitErrorContext>) {\n super(errorResponse);\n this.name = 'GitError';\n }\n\n // Type-safe accessors\n get repository() {\n return this.context.repository;\n }\n get branch() {\n return this.context.branch;\n }\n get targetDir() {\n return this.context.targetDir;\n }\n get stderr() {\n return this.context.stderr;\n }\n get exitCode() {\n return this.context.exitCode;\n }\n}\n\n// ============================================================================\n// Code Interpreter Errors\n// ============================================================================\n\n/**\n * Error thrown when interpreter is not ready\n */\nexport class InterpreterNotReadyError extends SandboxError<InterpreterNotReadyContext> {\n constructor(errorResponse: ErrorResponse<InterpreterNotReadyContext>) {\n super(errorResponse);\n this.name = 'InterpreterNotReadyError';\n }\n\n // Type-safe accessors\n get retryAfter() {\n return this.context.retryAfter;\n }\n get progress() {\n return this.context.progress;\n }\n}\n\n/**\n * Error thrown when a context is not found\n */\nexport class ContextNotFoundError extends SandboxError<ContextNotFoundContext> {\n constructor(errorResponse: ErrorResponse<ContextNotFoundContext>) {\n super(errorResponse);\n this.name = 'ContextNotFoundError';\n }\n\n // Type-safe accessor\n get contextId() {\n return this.context.contextId;\n }\n}\n\n/**\n * Error thrown when code execution fails\n */\nexport class CodeExecutionError extends SandboxError<CodeExecutionContext> {\n constructor(errorResponse: ErrorResponse<CodeExecutionContext>) {\n super(errorResponse);\n this.name = 'CodeExecutionError';\n }\n\n // Type-safe accessors\n get contextId() {\n return this.context.contextId;\n }\n get ename() {\n return this.context.ename;\n }\n get evalue() {\n return this.context.evalue;\n }\n get traceback() {\n return this.context.traceback;\n }\n}\n\n// ============================================================================\n// Validation Errors\n// ============================================================================\n\n/**\n * Error thrown when validation fails\n */\nexport class ValidationFailedError extends SandboxError<ValidationFailedContext> {\n constructor(errorResponse: ErrorResponse<ValidationFailedContext>) {\n super(errorResponse);\n this.name = 'ValidationFailedError';\n }\n\n // Type-safe accessor\n get validationErrors() {\n return this.context.validationErrors;\n }\n}\n","/**\n * Error adapter that converts ErrorResponse to appropriate Error class\n *\n * Simple switch statement - we trust the container sends correct context\n * No validation overhead since we control both sides\n */\n\nimport type {\n CodeExecutionContext,\n CommandErrorContext,\n CommandNotFoundContext,\n ContextNotFoundContext,\n ErrorResponse,\n FileExistsContext,\n FileNotFoundContext,\n FileSystemContext,\n GitAuthFailedContext,\n GitBranchNotFoundContext,\n GitErrorContext,\n GitRepositoryNotFoundContext,\n InternalErrorContext,\n InterpreterNotReadyContext,\n InvalidPortContext,\n PortAlreadyExposedContext,\n PortErrorContext,\n PortNotExposedContext,\n ProcessErrorContext,\n ProcessNotFoundContext,\n ValidationFailedContext\n} from '@repo/shared/errors';\nimport { ErrorCode } from '@repo/shared/errors';\n\nimport {\n CodeExecutionError,\n CommandError,\n CommandNotFoundError,\n ContextNotFoundError,\n CustomDomainRequiredError,\n FileExistsError,\n FileNotFoundError,\n FileSystemError,\n GitAuthenticationError,\n GitBranchNotFoundError,\n GitCheckoutError,\n GitCloneError,\n GitError,\n GitNetworkError,\n GitRepositoryNotFoundError,\n InterpreterNotReadyError,\n InvalidGitUrlError,\n InvalidPortError,\n PermissionDeniedError,\n PortAlreadyExposedError,\n PortError,\n PortInUseError,\n PortNotExposedError,\n ProcessError,\n ProcessNotFoundError,\n SandboxError,\n ServiceNotRespondingError,\n ValidationFailedError\n} from './classes';\n\n/**\n * Convert ErrorResponse to appropriate Error class\n * Simple switch statement - we trust the container sends correct context\n */\nexport function createErrorFromResponse(errorResponse: ErrorResponse): Error {\n // We trust the container sends correct context, use type assertions\n switch (errorResponse.code) {\n // File System Errors\n case ErrorCode.FILE_NOT_FOUND:\n return new FileNotFoundError(\n errorResponse as unknown as ErrorResponse<FileNotFoundContext>\n );\n\n case ErrorCode.FILE_EXISTS:\n return new FileExistsError(\n errorResponse as unknown as ErrorResponse<FileExistsContext>\n );\n\n case ErrorCode.PERMISSION_DENIED:\n return new PermissionDeniedError(\n errorResponse as unknown as ErrorResponse<FileSystemContext>\n );\n\n case ErrorCode.IS_DIRECTORY:\n case ErrorCode.NOT_DIRECTORY:\n case ErrorCode.NO_SPACE:\n case ErrorCode.TOO_MANY_FILES:\n case ErrorCode.RESOURCE_BUSY:\n case ErrorCode.READ_ONLY:\n case ErrorCode.NAME_TOO_LONG:\n case ErrorCode.TOO_MANY_LINKS:\n case ErrorCode.FILESYSTEM_ERROR:\n return new FileSystemError(\n errorResponse as unknown as ErrorResponse<FileSystemContext>\n );\n\n // Command Errors\n case ErrorCode.COMMAND_NOT_FOUND:\n return new CommandNotFoundError(\n errorResponse as unknown as ErrorResponse<CommandNotFoundContext>\n );\n\n case ErrorCode.COMMAND_PERMISSION_DENIED:\n case ErrorCode.COMMAND_EXECUTION_ERROR:\n case ErrorCode.INVALID_COMMAND:\n case ErrorCode.STREAM_START_ERROR:\n return new CommandError(\n errorResponse as unknown as ErrorResponse<CommandErrorContext>\n );\n\n // Process Errors\n case ErrorCode.PROCESS_NOT_FOUND:\n return new ProcessNotFoundError(\n errorResponse as unknown as ErrorResponse<ProcessNotFoundContext>\n );\n\n case ErrorCode.PROCESS_PERMISSION_DENIED:\n case ErrorCode.PROCESS_ERROR:\n return new ProcessError(\n errorResponse as unknown as ErrorResponse<ProcessErrorContext>\n );\n\n // Port Errors\n case ErrorCode.PORT_ALREADY_EXPOSED:\n return new PortAlreadyExposedError(\n errorResponse as unknown as ErrorResponse<PortAlreadyExposedContext>\n );\n\n case ErrorCode.PORT_NOT_EXPOSED:\n return new PortNotExposedError(\n errorResponse as unknown as ErrorResponse<PortNotExposedContext>\n );\n\n case ErrorCode.INVALID_PORT_NUMBER:\n case ErrorCode.INVALID_PORT:\n return new InvalidPortError(\n errorResponse as unknown as ErrorResponse<InvalidPortContext>\n );\n\n case ErrorCode.SERVICE_NOT_RESPONDING:\n return new ServiceNotRespondingError(\n errorResponse as unknown as ErrorResponse<PortErrorContext>\n );\n\n case ErrorCode.PORT_IN_USE:\n return new PortInUseError(\n errorResponse as unknown as ErrorResponse<PortErrorContext>\n );\n\n case ErrorCode.PORT_OPERATION_ERROR:\n return new PortError(\n errorResponse as unknown as ErrorResponse<PortErrorContext>\n );\n\n case ErrorCode.CUSTOM_DOMAIN_REQUIRED:\n return new CustomDomainRequiredError(\n errorResponse as unknown as ErrorResponse<InternalErrorContext>\n );\n\n // Git Errors\n case ErrorCode.GIT_REPOSITORY_NOT_FOUND:\n return new GitRepositoryNotFoundError(\n errorResponse as unknown as ErrorResponse<GitRepositoryNotFoundContext>\n );\n\n case ErrorCode.GIT_AUTH_FAILED:\n return new GitAuthenticationError(\n errorResponse as unknown as ErrorResponse<GitAuthFailedContext>\n );\n\n case ErrorCode.GIT_BRANCH_NOT_FOUND:\n return new GitBranchNotFoundError(\n errorResponse as unknown as ErrorResponse<GitBranchNotFoundContext>\n );\n\n case ErrorCode.GIT_NETWORK_ERROR:\n return new GitNetworkError(\n errorResponse as unknown as ErrorResponse<GitErrorContext>\n );\n\n case ErrorCode.GIT_CLONE_FAILED:\n return new GitCloneError(\n errorResponse as unknown as ErrorResponse<GitErrorContext>\n );\n\n case ErrorCode.GIT_CHECKOUT_FAILED:\n return new GitCheckoutError(\n errorResponse as unknown as ErrorResponse<GitErrorContext>\n );\n\n case ErrorCode.INVALID_GIT_URL:\n return new InvalidGitUrlError(\n errorResponse as unknown as ErrorResponse<ValidationFailedContext>\n );\n\n case ErrorCode.GIT_OPERATION_FAILED:\n return new GitError(\n errorResponse as unknown as ErrorResponse<GitErrorContext>\n );\n\n // Code Interpreter Errors\n case ErrorCode.INTERPRETER_NOT_READY:\n return new InterpreterNotReadyError(\n errorResponse as unknown as ErrorResponse<InterpreterNotReadyContext>\n );\n\n case ErrorCode.CONTEXT_NOT_FOUND:\n return new ContextNotFoundError(\n errorResponse as unknown as ErrorResponse<ContextNotFoundContext>\n );\n\n case ErrorCode.CODE_EXECUTION_ERROR:\n return new CodeExecutionError(\n errorResponse as unknown as ErrorResponse<CodeExecutionContext>\n );\n\n // Validation Errors\n case ErrorCode.VALIDATION_FAILED:\n return new ValidationFailedError(\n errorResponse as unknown as ErrorResponse<ValidationFailedContext>\n );\n\n // Generic Errors\n case ErrorCode.INVALID_JSON_RESPONSE:\n case ErrorCode.UNKNOWN_ERROR:\n case ErrorCode.INTERNAL_ERROR:\n return new SandboxError(\n errorResponse as unknown as ErrorResponse<InternalErrorContext>\n );\n\n default:\n // Fallback for unknown error codes\n return new SandboxError(errorResponse);\n }\n}\n","import type { Logger } from '@repo/shared';\nimport { createNoOpLogger } from '@repo/shared';\nimport { getHttpStatus } from '@repo/shared/errors';\nimport type { ErrorResponse as NewErrorResponse } from '../errors';\nimport { createErrorFromResponse, ErrorCode } from '../errors';\nimport type { SandboxError } from '../errors/classes';\nimport type { HttpClientOptions, ResponseHandler } from './types';\n\n// Container startup retry configuration\nconst TIMEOUT_MS = 120_000; // 2 minutes total retry budget\nconst MIN_TIME_FOR_RETRY_MS = 15_000; // Need at least 15s remaining to retry (allows for longer container startups)\n\n/**\n * Abstract base class providing common HTTP functionality for all domain clients\n */\nexport abstract class BaseHttpClient {\n protected baseUrl: string;\n protected options: HttpClientOptions;\n protected logger: Logger;\n\n constructor(options: HttpClientOptions = {}) {\n this.options = options;\n this.logger = options.logger ?? createNoOpLogger();\n this.baseUrl = this.options.baseUrl!;\n }\n\n /**\n * Core HTTP request method with automatic retry for container startup delays\n * Retries both 503 (provisioning) and 500 (startup failure) errors when they're container-related\n */\n protected async doFetch(\n path: string,\n options?: RequestInit\n ): Promise<Response> {\n const startTime = Date.now();\n let attempt = 0;\n\n while (true) {\n const response = await this.executeFetch(path, options);\n\n // Check if this is a retryable container error (both 500 and 503)\n const shouldRetry = await this.isRetryableContainerError(response);\n\n if (shouldRetry) {\n const elapsed = Date.now() - startTime;\n const remaining = TIMEOUT_MS - elapsed;\n\n // Check if we have enough time for another attempt\n if (remaining > MIN_TIME_FOR_RETRY_MS) {\n // Exponential backoff with longer delays for container ops: 3s, 6s, 12s, 24s, 30s\n const delay = Math.min(3000 * 2 ** attempt, 30000);\n\n this.logger.info('Container not ready, retrying', {\n status: response.status,\n attempt: attempt + 1,\n delayMs: delay,\n remainingSec: Math.floor(remaining / 1000)\n });\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n attempt++;\n continue;\n }\n\n // Timeout exhausted\n this.logger.error(\n 'Container failed to become ready',\n new Error(\n `Failed after ${attempt + 1} attempts over ${Math.floor(elapsed / 1000)}s`\n )\n );\n return response;\n }\n\n // Not a retryable error or request succeeded\n return response;\n }\n }\n\n /**\n * Make a POST request with JSON body\n */\n protected async post<T>(\n endpoint: string,\n data: unknown,\n responseHandler?: ResponseHandler<T>\n ): Promise<T> {\n const response = await this.doFetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n });\n\n return this.handleResponse(response, responseHandler);\n }\n\n /**\n * Make a GET request\n */\n protected async get<T>(\n endpoint: string,\n responseHandler?: ResponseHandler<T>\n ): Promise<T> {\n const response = await this.doFetch(endpoint, {\n method: 'GET'\n });\n\n return this.handleResponse(response, responseHandler);\n }\n\n /**\n * Make a DELETE request\n */\n protected async delete<T>(\n endpoint: string,\n responseHandler?: ResponseHandler<T>\n ): Promise<T> {\n const response = await this.doFetch(endpoint, {\n method: 'DELETE'\n });\n\n return this.handleResponse(response, responseHandler);\n }\n\n /**\n * Handle HTTP response with error checking and parsing\n */\n protected async handleResponse<T>(\n response: Response,\n customHandler?: ResponseHandler<T>\n ): Promise<T> {\n if (!response.ok) {\n await this.handleErrorResponse(response);\n }\n\n if (customHandler) {\n return customHandler(response);\n }\n\n try {\n return await response.json();\n } catch (error) {\n // Handle malformed JSON responses gracefully\n const errorResponse: NewErrorResponse = {\n code: ErrorCode.INVALID_JSON_RESPONSE,\n message: `Invalid JSON response: ${\n error instanceof Error ? error.message : 'Unknown parsing error'\n }`,\n context: {},\n httpStatus: response.status,\n timestamp: new Date().toISOString()\n };\n throw createErrorFromResponse(errorResponse);\n }\n }\n\n /**\n * Handle error responses with consistent error throwing\n */\n protected async handleErrorResponse(response: Response): Promise<never> {\n let errorData: NewErrorResponse;\n\n try {\n errorData = await response.json();\n } catch {\n // Fallback if response isn't JSON or parsing fails\n errorData = {\n code: ErrorCode.INTERNAL_ERROR,\n message: `HTTP error! status: ${response.status}`,\n context: { statusText: response.statusText },\n httpStatus: response.status,\n timestamp: new Date().toISOString()\n };\n }\n\n // Convert ErrorResponse to appropriate Error class\n const error = createErrorFromResponse(errorData);\n\n // Call error callback if provided\n this.options.onError?.(errorData.message, undefined);\n\n throw error;\n }\n\n /**\n * Create a streaming response handler for Server-Sent Events\n */\n protected async handleStreamResponse(\n response: Response\n ): Promise<ReadableStream<Uint8Array>> {\n if (!response.ok) {\n await this.handleErrorResponse(response);\n }\n\n if (!response.body) {\n throw new Error('No response body for streaming');\n }\n\n return response.body;\n }\n\n /**\n * Utility method to log successful operations\n */\n protected logSuccess(operation: string, details?: string): void {\n this.logger.info(\n `${operation} completed successfully`,\n details ? { details } : undefined\n );\n }\n\n /**\n * Utility method to log errors intelligently\n * Only logs unexpected errors (5xx), not expected errors (4xx)\n *\n * - 4xx errors (validation, not found, conflicts): Don't log (expected client errors)\n * - 5xx errors (server failures, internal errors): DO log (unexpected server errors)\n */\n protected logError(operation: string, error: unknown): void {\n // Check if it's a SandboxError with HTTP status\n if (error && typeof error === 'object' && 'httpStatus' in error) {\n const httpStatus = (error as SandboxError).httpStatus;\n\n // Only log server errors (5xx), not client errors (4xx)\n if (httpStatus >= 500) {\n this.logger.error(\n `Unexpected error in ${operation}`,\n error instanceof Error ? error : new Error(String(error)),\n { httpStatus }\n );\n }\n // 4xx errors are expected (validation, not found, etc.) - don't log\n } else {\n // Non-SandboxError (unexpected) - log it\n this.logger.error(\n `Error in ${operation}`,\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n\n /**\n * Check if response indicates a retryable container error\n * Uses fail-safe strategy: only retry known transient errors\n *\n * TODO: This relies on string matching error messages, which is brittle.\n * Ideally, the container API should return structured errors with a\n * `retryable: boolean` field to avoid coupling to error message format.\n *\n * @param response - HTTP response to check\n * @returns true if error is retryable container error, false otherwise\n */\n private async isRetryableContainerError(\n response: Response\n ): Promise<boolean> {\n // Only consider 500 and 503 status codes\n if (response.status !== 500 && response.status !== 503) {\n return false;\n }\n\n try {\n const cloned = response.clone();\n const text = await cloned.text();\n const textLower = text.toLowerCase();\n\n // Step 1: Check for permanent errors (fail fast)\n const permanentErrors = [\n 'no such image', // Missing Docker image\n 'container already exists', // Name collision\n 'malformed containerinspect' // Docker API issue\n ];\n\n if (permanentErrors.some((err) => textLower.includes(err))) {\n this.logger.debug('Detected permanent error, not retrying', { text });\n return false; // Don't retry\n }\n\n // Step 2: Check for known transient errors (do retry)\n const transientErrors = [\n // Platform provisioning (503)\n 'no container instance available',\n 'currently provisioning',\n\n // Port mapping race conditions (500)\n 'container port not found',\n 'connection refused: container port',\n\n // Application startup delays (500)\n 'the container is not listening',\n 'failed to verify port',\n 'container did not start',\n\n // Network transients (500)\n 'network connection lost',\n 'container suddenly disconnected',\n\n // Monitor race conditions (500)\n 'monitor failed to find container',\n\n // General timeouts (500)\n 'timed out',\n 'timeout'\n ];\n\n const shouldRetry = transientErrors.some((err) =>\n textLower.includes(err)\n );\n\n if (!shouldRetry) {\n this.logger.debug('Unknown error pattern, not retrying', {\n status: response.status,\n text: text.substring(0, 200) // Log first 200 chars\n });\n }\n\n return shouldRetry;\n } catch (error) {\n this.logger.error(\n 'Error checking if response is retryable',\n error instanceof Error ? error : new Error(String(error))\n );\n // If we can't read response, don't retry (fail fast)\n return false;\n }\n }\n\n private async executeFetch(\n path: string,\n options?: RequestInit\n ): Promise<Response> {\n const url = this.options.stub\n ? `http://localhost:${this.options.port}${path}`\n : `${this.baseUrl}${path}`;\n\n try {\n if (this.options.stub) {\n return await this.options.stub.containerFetch(\n url,\n options || {},\n this.options.port\n );\n } else {\n return await fetch(url, options);\n }\n } catch (error) {\n this.logger.error(\n 'HTTP request error',\n error instanceof Error ? error : new Error(String(error)),\n { method: options?.method || 'GET', url }\n );\n throw error;\n }\n }\n}\n","import type { ExecuteRequest } from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { BaseApiResponse } from './types';\n\n/**\n * Request interface for command execution\n */\nexport type { ExecuteRequest };\n\n/**\n * Response interface for command execution\n */\nexport interface ExecuteResponse extends BaseApiResponse {\n stdout: string;\n stderr: string;\n exitCode: number;\n command: string;\n}\n\n/**\n * Client for command execution operations\n */\nexport class CommandClient extends BaseHttpClient {\n /**\n * Execute a command and return the complete result\n * @param command - The command to execute\n * @param sessionId - The session ID for this command execution\n * @param timeoutMs - Optional timeout in milliseconds (unlimited by default)\n * @param env - Optional environment variables for this command\n * @param cwd - Optional working directory for this command\n */\n async execute(\n command: string,\n sessionId: string,\n options?: {\n timeoutMs?: number;\n env?: Record<string, string>;\n cwd?: string;\n }\n ): Promise<ExecuteResponse> {\n try {\n const data: ExecuteRequest = {\n command,\n sessionId,\n ...(options?.timeoutMs !== undefined && {\n timeoutMs: options.timeoutMs\n }),\n ...(options?.env !== undefined && { env: options.env }),\n ...(options?.cwd !== undefined && { cwd: options.cwd })\n };\n\n const response = await this.post<ExecuteResponse>('/api/execute', data);\n\n this.logSuccess(\n 'Command executed',\n `${command}, Success: ${response.success}`\n );\n\n // Call the callback if provided\n this.options.onCommandComplete?.(\n response.success,\n response.exitCode,\n response.stdout,\n response.stderr,\n response.command\n );\n\n return response;\n } catch (error) {\n this.logError('execute', error);\n\n // Call error callback if provided\n this.options.onError?.(\n error instanceof Error ? error.message : String(error),\n command\n );\n\n throw error;\n }\n }\n\n /**\n * Execute a command and return a stream of events\n * @param command - The command to execute\n * @param sessionId - The session ID for this command execution\n * @param options - Optional per-command execution settings\n */\n async executeStream(\n command: string,\n sessionId: string,\n options?: {\n timeoutMs?: number;\n env?: Record<string, string>;\n cwd?: string;\n }\n ): Promise<ReadableStream<Uint8Array>> {\n try {\n const data = {\n command,\n sessionId,\n ...(options?.timeoutMs !== undefined && {\n timeoutMs: options.timeoutMs\n }),\n ...(options?.env !== undefined && { env: options.env }),\n ...(options?.cwd !== undefined && { cwd: options.cwd })\n };\n\n const response = await this.doFetch('/api/execute/stream', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n });\n\n const stream = await this.handleStreamResponse(response);\n\n this.logSuccess('Command stream started', command);\n\n return stream;\n } catch (error) {\n this.logError('executeStream', error);\n\n // Call error callback if provided\n this.options.onError?.(\n error instanceof Error ? error.message : String(error),\n command\n );\n\n throw error;\n }\n }\n}\n","import type {\n DeleteFileResult,\n FileExistsResult,\n ListFilesOptions,\n ListFilesResult,\n MkdirResult,\n MoveFileResult,\n ReadFileResult,\n RenameFileResult,\n WriteFileResult\n} from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { HttpClientOptions, SessionRequest } from './types';\n\n/**\n * Request interface for creating directories\n */\nexport interface MkdirRequest extends SessionRequest {\n path: string;\n recursive?: boolean;\n}\n\n/**\n * Request interface for writing files\n */\nexport interface WriteFileRequest extends SessionRequest {\n path: string;\n content: string;\n encoding?: string;\n}\n\n/**\n * Request interface for reading files\n */\nexport interface ReadFileRequest extends SessionRequest {\n path: string;\n encoding?: string;\n}\n\n/**\n * Request interface for file operations (delete, rename, move)\n */\nexport interface FileOperationRequest extends SessionRequest {\n path: string;\n newPath?: string; // For rename/move operations\n}\n\n/**\n * Client for file system operations\n */\nexport class FileClient extends BaseHttpClient {\n /**\n * Create a directory\n * @param path - Directory path to create\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (recursive)\n */\n async mkdir(\n path: string,\n sessionId: string,\n options?: { recursive?: boolean }\n ): Promise<MkdirResult> {\n try {\n const data = {\n path,\n sessionId,\n recursive: options?.recursive ?? false\n };\n\n const response = await this.post<MkdirResult>('/api/mkdir', data);\n\n this.logSuccess(\n 'Directory created',\n `${path} (recursive: ${data.recursive})`\n );\n return response;\n } catch (error) {\n this.logError('mkdir', error);\n throw error;\n }\n }\n\n /**\n * Write content to a file\n * @param path - File path to write to\n * @param content - Content to write\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (encoding)\n */\n async writeFile(\n path: string,\n content: string,\n sessionId: string,\n options?: { encoding?: string }\n ): Promise<WriteFileResult> {\n try {\n const data = {\n path,\n content,\n sessionId,\n encoding: options?.encoding\n };\n\n const response = await this.post<WriteFileResult>('/api/write', data);\n\n this.logSuccess('File written', `${path} (${content.length} chars)`);\n return response;\n } catch (error) {\n this.logError('writeFile', error);\n throw error;\n }\n }\n\n /**\n * Read content from a file\n * @param path - File path to read from\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (encoding)\n */\n async readFile(\n path: string,\n sessionId: string,\n options?: { encoding?: string }\n ): Promise<ReadFileResult> {\n try {\n const data = {\n path,\n sessionId,\n encoding: options?.encoding\n };\n\n const response = await this.post<ReadFileResult>('/api/read', data);\n\n this.logSuccess(\n 'File read',\n `${path} (${response.content.length} chars)`\n );\n return response;\n } catch (error) {\n this.logError('readFile', error);\n throw error;\n }\n }\n\n /**\n * Stream a file using Server-Sent Events\n * Returns a ReadableStream of SSE events containing metadata, chunks, and completion\n * @param path - File path to stream\n * @param sessionId - The session ID for this operation\n */\n async readFileStream(\n path: string,\n sessionId: string\n ): Promise<ReadableStream<Uint8Array>> {\n try {\n const data = {\n path,\n sessionId\n };\n\n const response = await this.doFetch('/api/read/stream', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n });\n\n const stream = await this.handleStreamResponse(response);\n this.logSuccess('File stream started', path);\n return stream;\n } catch (error) {\n this.logError('readFileStream', error);\n throw error;\n }\n }\n\n /**\n * Delete a file\n * @param path - File path to delete\n * @param sessionId - The session ID for this operation\n */\n async deleteFile(path: string, sessionId: string): Promise<DeleteFileResult> {\n try {\n const data = { path, sessionId };\n\n const response = await this.post<DeleteFileResult>('/api/delete', data);\n\n this.logSuccess('File deleted', path);\n return response;\n } catch (error) {\n this.logError('deleteFile', error);\n throw error;\n }\n }\n\n /**\n * Rename a file\n * @param path - Current file path\n * @param newPath - New file path\n * @param sessionId - The session ID for this operation\n */\n async renameFile(\n path: string,\n newPath: string,\n sessionId: string\n ): Promise<RenameFileResult> {\n try {\n const data = { oldPath: path, newPath, sessionId };\n\n const response = await this.post<RenameFileResult>('/api/rename', data);\n\n this.logSuccess('File renamed', `${path} -> ${newPath}`);\n return response;\n } catch (error) {\n this.logError('renameFile', error);\n throw error;\n }\n }\n\n /**\n * Move a file\n * @param path - Current file path\n * @param newPath - Destination file path\n * @param sessionId - The session ID for this operation\n */\n async moveFile(\n path: string,\n newPath: string,\n sessionId: string\n ): Promise<MoveFileResult> {\n try {\n const data = { sourcePath: path, destinationPath: newPath, sessionId };\n\n const response = await this.post<MoveFileResult>('/api/move', data);\n\n this.logSuccess('File moved', `${path} -> ${newPath}`);\n return response;\n } catch (error) {\n this.logError('moveFile', error);\n throw error;\n }\n }\n\n /**\n * List files in a directory\n * @param path - Directory path to list\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (recursive, includeHidden)\n */\n async listFiles(\n path: string,\n sessionId: string,\n options?: ListFilesOptions\n ): Promise<ListFilesResult> {\n try {\n const data = {\n path,\n sessionId,\n options: options || {}\n };\n\n const response = await this.post<ListFilesResult>(\n '/api/list-files',\n data\n );\n\n this.logSuccess('Files listed', `${path} (${response.count} files)`);\n return response;\n } catch (error) {\n this.logError('listFiles', error);\n throw error;\n }\n }\n\n /**\n * Check if a file or directory exists\n * @param path - Path to check\n * @param sessionId - The session ID for this operation\n */\n async exists(path: string, sessionId: string): Promise<FileExistsResult> {\n try {\n const data = {\n path,\n sessionId\n };\n\n const response = await this.post<FileExistsResult>('/api/exists', data);\n\n this.logSuccess(\n 'Path existence checked',\n `${path} (exists: ${response.exists})`\n );\n return response;\n } catch (error) {\n this.logError('exists', error);\n throw error;\n }\n }\n}\n","import type { GitCheckoutResult } from '@repo/shared';\nimport { GitLogger } from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { HttpClientOptions, SessionRequest } from './types';\n\n// Re-export for convenience\nexport type { GitCheckoutResult };\n\n/**\n * Request interface for Git checkout operations\n */\nexport interface GitCheckoutRequest extends SessionRequest {\n repoUrl: string;\n branch?: string;\n targetDir?: string;\n}\n\n/**\n * Client for Git repository operations\n */\nexport class GitClient extends BaseHttpClient {\n constructor(options: HttpClientOptions = {}) {\n super(options);\n // Wrap logger with GitLogger to auto-redact credentials\n this.logger = new GitLogger(this.logger);\n }\n\n /**\n * Clone a Git repository\n * @param repoUrl - URL of the Git repository to clone\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (branch, targetDir)\n */\n async checkout(\n repoUrl: string,\n sessionId: string,\n options?: {\n branch?: string;\n targetDir?: string;\n }\n ): Promise<GitCheckoutResult> {\n try {\n // Determine target directory - use provided path or generate from repo name\n let targetDir = options?.targetDir;\n if (!targetDir) {\n const repoName = this.extractRepoName(repoUrl);\n // Ensure absolute path in /workspace\n targetDir = `/workspace/${repoName}`;\n }\n\n const data: GitCheckoutRequest = {\n repoUrl,\n sessionId,\n targetDir\n };\n\n // Only include branch if explicitly specified\n // This allows Git to use the repository's default branch\n if (options?.branch) {\n data.branch = options.branch;\n }\n\n const response = await this.post<GitCheckoutResult>(\n '/api/git/checkout',\n data\n );\n\n this.logSuccess(\n 'Repository cloned',\n `${repoUrl} (branch: ${response.branch}) -> ${response.targetDir}`\n );\n\n return response;\n } catch (error) {\n this.logError('checkout', error);\n throw error;\n }\n }\n\n /**\n * Extract repository name from URL for default directory name\n */\n private extractRepoName(repoUrl: string): string {\n try {\n const url = new URL(repoUrl);\n const pathParts = url.pathname.split('/');\n const repoName = pathParts[pathParts.length - 1];\n\n // Remove .git extension if present\n return repoName.replace(/\\.git$/, '');\n } catch {\n // Fallback for invalid URLs\n const parts = repoUrl.split('/');\n const repoName = parts[parts.length - 1];\n return repoName.replace(/\\.git$/, '') || 'repo';\n }\n }\n}\n","import {\n type CodeContext,\n type ContextCreateResult,\n type ContextListResult,\n type CreateContextOptions,\n type ExecutionError,\n type OutputMessage,\n type Result,\n ResultImpl\n} from '@repo/shared';\nimport type { ErrorResponse } from '../errors';\nimport {\n createErrorFromResponse,\n ErrorCode,\n InterpreterNotReadyError\n} from '../errors';\nimport { BaseHttpClient } from './base-client.js';\nimport type { HttpClientOptions } from './types.js';\n\n// Streaming execution data from the server\ninterface StreamingExecutionData {\n type: 'result' | 'stdout' | 'stderr' | 'error' | 'execution_complete';\n text?: string;\n html?: string;\n png?: string; // base64\n jpeg?: string; // base64\n svg?: string;\n latex?: string;\n markdown?: string;\n javascript?: string;\n json?: unknown;\n chart?: {\n type:\n | 'line'\n | 'bar'\n | 'scatter'\n | 'pie'\n | 'histogram'\n | 'heatmap'\n | 'unknown';\n data: unknown;\n options?: unknown;\n };\n data?: unknown;\n metadata?: Record<string, unknown>;\n execution_count?: number;\n ename?: string;\n evalue?: string;\n traceback?: string[];\n lineNumber?: number;\n timestamp?: number;\n}\n\nexport interface ExecutionCallbacks {\n onStdout?: (output: OutputMessage) => void | Promise<void>;\n onStderr?: (output: OutputMessage) => void | Promise<void>;\n onResult?: (result: Result) => void | Promise<void>;\n onError?: (error: ExecutionError) => void | Promise<void>;\n}\n\nexport class InterpreterClient extends BaseHttpClient {\n private readonly maxRetries = 3;\n private readonly retryDelayMs = 1000;\n\n async createCodeContext(\n options: CreateContextOptions = {}\n ): Promise<CodeContext> {\n return this.executeWithRetry(async () => {\n const response = await this.doFetch('/api/contexts', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n language: options.language || 'python',\n cwd: options.cwd || '/workspace',\n env_vars: options.envVars\n })\n });\n\n if (!response.ok) {\n const error = await this.parseErrorResponse(response);\n throw error;\n }\n\n const data = (await response.json()) as ContextCreateResult;\n if (!data.success) {\n throw new Error(`Failed to create context: ${JSON.stringify(data)}`);\n }\n\n return {\n id: data.contextId,\n language: data.language,\n cwd: data.cwd || '/workspace',\n createdAt: new Date(data.timestamp),\n lastUsed: new Date(data.timestamp)\n };\n });\n }\n\n async runCodeStream(\n contextId: string | undefined,\n code: string,\n language: string | undefined,\n callbacks: ExecutionCallbacks,\n timeoutMs?: number\n ): Promise<void> {\n return this.executeWithRetry(async () => {\n const response = await this.doFetch('/api/execute/code', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream'\n },\n body: JSON.stringify({\n context_id: contextId,\n code,\n language,\n ...(timeoutMs !== undefined && { timeout_ms: timeoutMs })\n })\n });\n\n if (!response.ok) {\n const error = await this.parseErrorResponse(response);\n throw error;\n }\n\n if (!response.body) {\n throw new Error('No response body for streaming execution');\n }\n\n // Process streaming response\n for await (const chunk of this.readLines(response.body)) {\n await this.parseExecutionResult(chunk, callbacks);\n }\n });\n }\n\n async listCodeContexts(): Promise<CodeContext[]> {\n return this.executeWithRetry(async () => {\n const response = await this.doFetch('/api/contexts', {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' }\n });\n\n if (!response.ok) {\n const error = await this.parseErrorResponse(response);\n throw error;\n }\n\n const data = (await response.json()) as ContextListResult;\n if (!data.success) {\n throw new Error(`Failed to list contexts: ${JSON.stringify(data)}`);\n }\n\n return data.contexts.map((ctx) => ({\n id: ctx.id,\n language: ctx.language,\n cwd: ctx.cwd || '/workspace',\n createdAt: new Date(data.timestamp),\n lastUsed: new Date(data.timestamp)\n }));\n });\n }\n\n async deleteCodeContext(contextId: string): Promise<void> {\n return this.executeWithRetry(async () => {\n const response = await this.doFetch(`/api/contexts/${contextId}`, {\n method: 'DELETE',\n headers: { 'Content-Type': 'application/json' }\n });\n\n if (!response.ok) {\n const error = await this.parseErrorResponse(response);\n throw error;\n }\n });\n }\n\n /**\n * Execute an operation with automatic retry for transient errors\n */\n private async executeWithRetry<T>(operation: () => Promise<T>): Promise<T> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt < this.maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n this.logError('executeWithRetry', error);\n lastError = error as Error;\n\n // Check if it's a retryable error (interpreter not ready)\n if (this.isRetryableError(error)) {\n // Don't retry on the last attempt\n if (attempt < this.maxRetries - 1) {\n // Exponential backoff with jitter\n const delay =\n this.retryDelayMs * 2 ** attempt + Math.random() * 1000;\n await new Promise((resolve) => setTimeout(resolve, delay));\n continue;\n }\n }\n\n // Not retryable or last attempt - throw the error\n throw error;\n }\n }\n\n throw lastError || new Error('Execution failed after retries');\n }\n\n private isRetryableError(error: unknown): boolean {\n if (error instanceof InterpreterNotReadyError) {\n return true;\n }\n\n if (error instanceof Error) {\n return (\n error.message.includes('not ready') ||\n error.message.includes('initializing')\n );\n }\n\n return false;\n }\n\n private async parseErrorResponse(response: Response): Promise<Error> {\n try {\n const errorData = (await response.json()) as ErrorResponse;\n return createErrorFromResponse(errorData);\n } catch {\n // Fallback if response isn't JSON\n const errorResponse: ErrorResponse = {\n code: ErrorCode.INTERNAL_ERROR,\n message: `HTTP ${response.status}: ${response.statusText}`,\n context: {},\n httpStatus: response.status,\n timestamp: new Date().toISOString()\n };\n return createErrorFromResponse(errorResponse);\n }\n }\n\n private async *readLines(\n stream: ReadableStream<Uint8Array>\n ): AsyncGenerator<string> {\n const reader = stream.getReader();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (value) {\n buffer += new TextDecoder().decode(value);\n }\n if (done) break;\n\n let newlineIdx = buffer.indexOf('\\n');\n while (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx);\n buffer = buffer.slice(newlineIdx + 1);\n newlineIdx = buffer.indexOf('\\n');\n }\n }\n\n // Yield any remaining data\n if (buffer.length > 0) {\n yield buffer;\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n private async parseExecutionResult(\n line: string,\n callbacks: ExecutionCallbacks\n ) {\n if (!line.trim()) return;\n\n // Skip lines that don't start with \"data: \" (SSE format)\n if (!line.startsWith('data: ')) return;\n\n try {\n // Strip \"data: \" prefix and parse JSON\n const jsonData = line.substring(6); // \"data: \" is 6 characters\n const data = JSON.parse(jsonData) as StreamingExecutionData;\n\n switch (data.type) {\n case 'stdout':\n if (callbacks.onStdout && data.text) {\n await callbacks.onStdout({\n text: data.text,\n timestamp: data.timestamp || Date.now()\n });\n }\n break;\n\n case 'stderr':\n if (callbacks.onStderr && data.text) {\n await callbacks.onStderr({\n text: data.text,\n timestamp: data.timestamp || Date.now()\n });\n }\n break;\n\n case 'result':\n if (callbacks.onResult) {\n // Create a ResultImpl instance from the raw data\n const result = new ResultImpl(data);\n await callbacks.onResult(result);\n }\n break;\n\n case 'error':\n if (callbacks.onError) {\n await callbacks.onError({\n name: data.ename || 'Error',\n message: data.evalue || 'Unknown error',\n traceback: data.traceback || []\n });\n }\n break;\n\n case 'execution_complete':\n // Signal completion - callbacks can handle cleanup if needed\n break;\n }\n } catch (error) {\n this.logError('parseExecutionResult', error);\n }\n }\n}\n","import type {\n PortCloseResult,\n PortExposeResult,\n PortListResult\n} from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { HttpClientOptions } from './types';\n\n// Re-export for convenience\nexport type { PortExposeResult, PortCloseResult, PortListResult };\n\n/**\n * Request interface for exposing ports\n */\nexport interface ExposePortRequest {\n port: number;\n name?: string;\n}\n\n/**\n * Request interface for unexposing ports\n */\nexport interface UnexposePortRequest {\n port: number;\n}\n\n/**\n * Client for port management and preview URL operations\n */\nexport class PortClient extends BaseHttpClient {\n /**\n * Expose a port and get a preview URL\n * @param port - Port number to expose\n * @param sessionId - The session ID for this operation\n * @param name - Optional name for the port\n */\n async exposePort(\n port: number,\n sessionId: string,\n name?: string\n ): Promise<PortExposeResult> {\n try {\n const data = { port, sessionId, name };\n\n const response = await this.post<PortExposeResult>(\n '/api/expose-port',\n data\n );\n\n this.logSuccess(\n 'Port exposed',\n `${port} exposed at ${response.url}${name ? ` (${name})` : ''}`\n );\n\n return response;\n } catch (error) {\n this.logError('exposePort', error);\n throw error;\n }\n }\n\n /**\n * Unexpose a port and remove its preview URL\n * @param port - Port number to unexpose\n * @param sessionId - The session ID for this operation\n */\n async unexposePort(\n port: number,\n sessionId: string\n ): Promise<PortCloseResult> {\n try {\n const url = `/api/exposed-ports/${port}?session=${encodeURIComponent(\n sessionId\n )}`;\n const response = await this.delete<PortCloseResult>(url);\n\n this.logSuccess('Port unexposed', `${port}`);\n return response;\n } catch (error) {\n this.logError('unexposePort', error);\n throw error;\n }\n }\n\n /**\n * Get all currently exposed ports\n * @param sessionId - The session ID for this operation\n */\n async getExposedPorts(sessionId: string): Promise<PortListResult> {\n try {\n const url = `/api/exposed-ports?session=${encodeURIComponent(sessionId)}`;\n const response = await this.get<PortListResult>(url);\n\n this.logSuccess(\n 'Exposed ports retrieved',\n `${response.ports.length} ports exposed`\n );\n\n return response;\n } catch (error) {\n this.logError('getExposedPorts', error);\n throw error;\n }\n }\n}\n","import type {\n ProcessCleanupResult,\n ProcessInfoResult,\n ProcessKillResult,\n ProcessListResult,\n ProcessLogsResult,\n ProcessStartResult,\n StartProcessRequest\n} from '@repo/shared';\nimport { BaseHttpClient } from './base-client';\nimport type { HttpClientOptions } from './types';\n\n// Re-export for convenience\nexport type {\n StartProcessRequest,\n ProcessStartResult,\n ProcessListResult,\n ProcessInfoResult,\n ProcessKillResult,\n ProcessLogsResult,\n ProcessCleanupResult\n};\n\n/**\n * Client for background process management\n */\nexport class ProcessClient extends BaseHttpClient {\n /**\n * Start a background process\n * @param command - Command to execute as a background process\n * @param sessionId - The session ID for this operation\n * @param options - Optional settings (processId)\n */\n async startProcess(\n command: string,\n sessionId: string,\n options?: {\n processId?: string;\n timeoutMs?: number;\n env?: Record<string, string>;\n cwd?: string;\n encoding?: string;\n autoCleanup?: boolean;\n }\n ): Promise<ProcessStartResult> {\n try {\n const data: StartProcessRequest = {\n command,\n sessionId,\n ...(options?.processId !== undefined && {\n processId: options.processId\n }),\n ...(options?.timeoutMs !== undefined && {\n timeoutMs: options.timeoutMs\n }),\n ...(options?.env !== undefined && { env: options.env }),\n ...(options?.cwd !== undefined && { cwd: options.cwd }),\n ...(options?.encoding !== undefined && { encoding: options.encoding }),\n ...(options?.autoCleanup !== undefined && {\n autoCleanup: options.autoCleanup\n })\n };\n\n const response = await this.post<ProcessStartResult>(\n '/api/process/start',\n data\n );\n\n this.logSuccess(\n 'Process started',\n `${command} (ID: ${response.processId})`\n );\n\n return response;\n } catch (error) {\n this.logError('startProcess', error);\n throw error;\n }\n }\n\n /**\n * List all processes (sandbox-scoped, not session-scoped)\n */\n async listProcesses(): Promise<ProcessListResult> {\n try {\n const url = `/api/process/list`;\n const response = await this.get<ProcessListResult>(url);\n\n this.logSuccess(\n 'Processes listed',\n `${response.processes.length} processes`\n );\n return response;\n } catch (error) {\n this.logError('listProcesses', error);\n throw error;\n }\n }\n\n /**\n * Get information about a specific process (sandbox-scoped, not session-scoped)\n * @param processId - ID of the process to retrieve\n */\n async getProcess(processId: string): Promise<ProcessInfoResult> {\n try {\n const url = `/api/process/${processId}`;\n const response = await this.get<ProcessInfoResult>(url);\n\n this.logSuccess('Process retrieved', `ID: ${processId}`);\n return response;\n } catch (error) {\n this.logError('getProcess', error);\n throw error;\n }\n }\n\n /**\n * Kill a specific process (sandbox-scoped, not session-scoped)\n * @param processId - ID of the process to kill\n */\n async killProcess(processId: string): Promise<ProcessKillResult> {\n try {\n const url = `/api/process/${processId}`;\n const response = await this.delete<ProcessKillResult>(url);\n\n this.logSuccess('Process killed', `ID: ${processId}`);\n return response;\n } catch (error) {\n this.logError('killProcess', error);\n throw error;\n }\n }\n\n /**\n * Kill all running processes (sandbox-scoped, not session-scoped)\n */\n async killAllProcesses(): Promise<ProcessCleanupResult> {\n try {\n const url = `/api/process/kill-all`;\n const response = await this.delete<ProcessCleanupResult>(url);\n\n this.logSuccess(\n 'All processes killed',\n `${response.cleanedCount} processes terminated`\n );\n\n return response;\n } catch (error) {\n this.logError('killAllProcesses', error);\n throw error;\n }\n }\n\n /**\n * Get logs from a specific process (sandbox-scoped, not session-scoped)\n * @param processId - ID of the process to get logs from\n */\n async getProcessLogs(processId: string): Promise<ProcessLogsResult> {\n try {\n const url = `/api/process/${processId}/logs`;\n const response = await this.get<ProcessLogsResult>(url);\n\n this.logSuccess(\n 'Process logs retrieved',\n `ID: ${processId}, stdout: ${response.stdout.length} chars, stderr: ${response.stderr.length} chars`\n );\n\n return response;\n } catch (error) {\n this.logError('getProcessLogs', error);\n throw error;\n }\n }\n\n /**\n * Stream logs from a specific process (sandbox-scoped, not session-scoped)\n * @param processId - ID of the process to stream logs from\n */\n async streamProcessLogs(\n processId: string\n ): Promise<ReadableStream<Uint8Array>> {\n try {\n const url = `/api/process/${processId}/stream`;\n const response = await this.doFetch(url, {\n method: 'GET'\n });\n\n const stream = await this.handleStreamResponse(response);\n\n this.logSuccess('Process log stream started', `ID: ${processId}`);\n\n return stream;\n } catch (error) {\n this.logError('streamProcessLogs', error);\n throw error;\n }\n }\n}\n","import { BaseHttpClient } from './base-client';\nimport type { BaseApiResponse, HttpClientOptions } from './types';\n\n/**\n * Response interface for ping operations\n */\nexport interface PingResponse extends BaseApiResponse {\n message: string;\n uptime?: number;\n}\n\n/**\n * Response interface for getting available commands\n */\nexport interface CommandsResponse extends BaseApiResponse {\n availableCommands: string[];\n count: number;\n}\n\n/**\n * Response interface for getting container version\n */\nexport interface VersionResponse extends BaseApiResponse {\n version: string;\n}\n\n/**\n * Request interface for creating sessions\n */\nexport interface CreateSessionRequest {\n id: string;\n env?: Record<string, string>;\n cwd?: string;\n}\n\n/**\n * Response interface for creating sessions\n */\nexport interface CreateSessionResponse extends BaseApiResponse {\n id: string;\n message: string;\n}\n\n/**\n * Request interface for deleting sessions\n */\nexport interface DeleteSessionRequest {\n sessionId: string;\n}\n\n/**\n * Response interface for deleting sessions\n */\nexport interface DeleteSessionResponse extends BaseApiResponse {\n sessionId: string;\n}\n\n/**\n * Client for health checks and utility operations\n */\nexport class UtilityClient extends BaseHttpClient {\n /**\n * Ping the sandbox to check if it's responsive\n */\n async ping(): Promise<string> {\n try {\n const response = await this.get<PingResponse>('/api/ping');\n\n this.logSuccess('Ping successful', response.message);\n return response.message;\n } catch (error) {\n this.logError('ping', error);\n throw error;\n }\n }\n\n /**\n * Get list of available commands in the sandbox environment\n */\n async getCommands(): Promise<string[]> {\n try {\n const response = await this.get<CommandsResponse>('/api/commands');\n\n this.logSuccess(\n 'Commands retrieved',\n `${response.count} commands available`\n );\n\n return response.availableCommands;\n } catch (error) {\n this.logError('getCommands', error);\n throw error;\n }\n }\n\n /**\n * Create a new execution session\n * @param options - Session configuration (id, env, cwd)\n */\n async createSession(\n options: CreateSessionRequest\n ): Promise<CreateSessionResponse> {\n try {\n const response = await this.post<CreateSessionResponse>(\n '/api/session/create',\n options\n );\n\n this.logSuccess('Session created', `ID: ${options.id}`);\n return response;\n } catch (error) {\n this.logError('createSession', error);\n throw error;\n }\n }\n\n /**\n * Delete an execution session\n * @param sessionId - Session ID to delete\n */\n async deleteSession(sessionId: string): Promise<DeleteSessionResponse> {\n try {\n const response = await this.post<DeleteSessionResponse>(\n '/api/session/delete',\n { sessionId }\n );\n\n this.logSuccess('Session deleted', `ID: ${sessionId}`);\n return response;\n } catch (error) {\n this.logError('deleteSession', error);\n throw error;\n }\n }\n\n /**\n * Get the container version\n * Returns the version embedded in the Docker image during build\n */\n async getVersion(): Promise<string> {\n try {\n const response = await this.get<VersionResponse>('/api/version');\n\n this.logSuccess('Version retrieved', response.version);\n return response.version;\n } catch (error) {\n // If version endpoint doesn't exist (old container), return 'unknown'\n // This allows for backward compatibility\n this.logger.debug(\n 'Failed to get container version (may be old container)',\n { error }\n );\n return 'unknown';\n }\n }\n}\n","import { CommandClient } from './command-client';\nimport { FileClient } from './file-client';\nimport { GitClient } from './git-client';\nimport { InterpreterClient } from './interpreter-client';\nimport { PortClient } from './port-client';\nimport { ProcessClient } from './process-client';\nimport type { HttpClientOptions } from './types';\nimport { UtilityClient } from './utility-client';\n\n/**\n * Main sandbox client that composes all domain-specific clients\n * Provides organized access to all sandbox functionality\n */\nexport class SandboxClient {\n public readonly commands: CommandClient;\n public readonly files: FileClient;\n public readonly processes: ProcessClient;\n public readonly ports: PortClient;\n public readonly git: GitClient;\n public readonly interpreter: InterpreterClient;\n public readonly utils: UtilityClient;\n\n constructor(options: HttpClientOptions) {\n // Ensure baseUrl is provided for all clients\n const clientOptions: HttpClientOptions = {\n baseUrl: 'http://localhost:3000',\n ...options\n };\n\n // Initialize all domain clients with shared options\n this.commands = new CommandClient(clientOptions);\n this.files = new FileClient(clientOptions);\n this.processes = new ProcessClient(clientOptions);\n this.ports = new PortClient(clientOptions);\n this.git = new GitClient(clientOptions);\n this.interpreter = new InterpreterClient(clientOptions);\n this.utils = new UtilityClient(clientOptions);\n }\n}\n","/**\n * Security utilities for URL construction and input validation\n *\n * This module contains critical security functions to prevent:\n * - URL injection attacks\n * - SSRF (Server-Side Request Forgery) attacks\n * - DNS rebinding attacks\n * - Host header injection\n * - Open redirect vulnerabilities\n */\n\nexport class SecurityError extends Error {\n constructor(\n message: string,\n public readonly code?: string\n ) {\n super(message);\n this.name = 'SecurityError';\n }\n}\n\n/**\n * Validates port numbers for sandbox services\n * Only allows non-system ports to prevent conflicts and security issues\n */\nexport function validatePort(port: number): boolean {\n // Must be a valid integer\n if (!Number.isInteger(port)) {\n return false;\n }\n\n // Only allow non-system ports (1024-65535)\n if (port < 1024 || port > 65535) {\n return false;\n }\n\n // Exclude ports reserved by our system\n const reservedPorts = [\n 3000, // Control plane port\n 8787 // Common wrangler dev port\n ];\n\n if (reservedPorts.includes(port)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Sanitizes and validates sandbox IDs for DNS compliance and security\n * Only enforces critical requirements - allows maximum developer flexibility\n */\nexport function sanitizeSandboxId(id: string): string {\n // Basic validation: not empty, reasonable length limit (DNS subdomain limit is 63 chars)\n if (!id || id.length > 63) {\n throw new SecurityError(\n 'Sandbox ID must be 1-63 characters long.',\n 'INVALID_SANDBOX_ID_LENGTH'\n );\n }\n\n // DNS compliance: cannot start or end with hyphens (RFC requirement)\n if (id.startsWith('-') || id.endsWith('-')) {\n throw new SecurityError(\n 'Sandbox ID cannot start or end with hyphens (DNS requirement).',\n 'INVALID_SANDBOX_ID_HYPHENS'\n );\n }\n\n // Prevent reserved names that cause technical conflicts\n const reservedNames = [\n 'www',\n 'api',\n 'admin',\n 'root',\n 'system',\n 'cloudflare',\n 'workers'\n ];\n\n const lowerCaseId = id.toLowerCase();\n if (reservedNames.includes(lowerCaseId)) {\n throw new SecurityError(\n `Reserved sandbox ID '${id}' is not allowed.`,\n 'RESERVED_SANDBOX_ID'\n );\n }\n\n return id;\n}\n\n/**\n * Validates language for code interpreter\n * Only allows supported languages\n */\nexport function validateLanguage(language: string | undefined): void {\n if (!language) {\n return; // undefined is valid, will default to python\n }\n\n const supportedLanguages = [\n 'python',\n 'python3',\n 'javascript',\n 'js',\n 'node',\n 'typescript',\n 'ts'\n ];\n const normalized = language.toLowerCase();\n\n if (!supportedLanguages.includes(normalized)) {\n throw new SecurityError(\n `Unsupported language '${language}'. Supported languages: python, javascript, typescript`,\n 'INVALID_LANGUAGE'\n );\n }\n}\n","import {\n type CodeContext,\n type CreateContextOptions,\n Execution,\n type ExecutionError,\n type OutputMessage,\n type Result,\n ResultImpl,\n type RunCodeOptions\n} from '@repo/shared';\nimport type { InterpreterClient } from './clients/interpreter-client.js';\nimport type { Sandbox } from './sandbox.js';\nimport { validateLanguage } from './security.js';\n\nexport class CodeInterpreter {\n private interpreterClient: InterpreterClient;\n private contexts = new Map<string, CodeContext>();\n\n constructor(sandbox: Sandbox) {\n // In init-testing architecture, client is a SandboxClient with an interpreter property\n this.interpreterClient = (sandbox.client as any)\n .interpreter as InterpreterClient;\n }\n\n /**\n * Create a new code execution context\n */\n async createCodeContext(\n options: CreateContextOptions = {}\n ): Promise<CodeContext> {\n // Validate language before sending to container\n validateLanguage(options.language);\n\n const context = await this.interpreterClient.createCodeContext(options);\n this.contexts.set(context.id, context);\n return context;\n }\n\n /**\n * Run code with optional context\n */\n async runCode(\n code: string,\n options: RunCodeOptions = {}\n ): Promise<Execution> {\n // Get or create context\n let context = options.context;\n if (!context) {\n // Try to find or create a default context for the language\n const language = options.language || 'python';\n context = await this.getOrCreateDefaultContext(language);\n }\n\n // Create execution object to collect results\n const execution = new Execution(code, context);\n\n // Stream execution\n await this.interpreterClient.runCodeStream(\n context.id,\n code,\n options.language,\n {\n onStdout: (output: OutputMessage) => {\n execution.logs.stdout.push(output.text);\n if (options.onStdout) return options.onStdout(output);\n },\n onStderr: (output: OutputMessage) => {\n execution.logs.stderr.push(output.text);\n if (options.onStderr) return options.onStderr(output);\n },\n onResult: async (result: Result) => {\n execution.results.push(new ResultImpl(result) as any);\n if (options.onResult) return options.onResult(result);\n },\n onError: (error: ExecutionError) => {\n execution.error = error;\n if (options.onError) return options.onError(error);\n }\n }\n );\n\n return execution;\n }\n\n /**\n * Run code and return a streaming response\n */\n async runCodeStream(\n code: string,\n options: RunCodeOptions = {}\n ): Promise<ReadableStream> {\n // Get or create context\n let context = options.context;\n if (!context) {\n const language = options.language || 'python';\n context = await this.getOrCreateDefaultContext(language);\n }\n\n // Create streaming response\n // Note: doFetch is protected but we need direct access for raw stream response\n const response = await (this.interpreterClient as any).doFetch(\n '/api/execute/code',\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream'\n },\n body: JSON.stringify({\n context_id: context.id,\n code,\n language: options.language\n })\n }\n );\n\n if (!response.ok) {\n const errorData = (await response\n .json()\n .catch(() => ({ error: 'Unknown error' }))) as { error?: string };\n throw new Error(\n errorData.error || `Failed to execute code: ${response.status}`\n );\n }\n\n if (!response.body) {\n throw new Error('No response body for streaming execution');\n }\n\n return response.body;\n }\n\n /**\n * List all code contexts\n */\n async listCodeContexts(): Promise<CodeContext[]> {\n const contexts = await this.interpreterClient.listCodeContexts();\n\n // Update local cache\n for (const context of contexts) {\n this.contexts.set(context.id, context);\n }\n\n return contexts;\n }\n\n /**\n * Delete a code context\n */\n async deleteCodeContext(contextId: string): Promise<void> {\n await this.interpreterClient.deleteCodeContext(contextId);\n this.contexts.delete(contextId);\n }\n\n private async getOrCreateDefaultContext(\n language: 'python' | 'javascript' | 'typescript'\n ): Promise<CodeContext> {\n // Check if we have a cached context for this language\n for (const context of this.contexts.values()) {\n if (context.language === language) {\n return context;\n }\n }\n\n // Create new default context\n return this.createCodeContext({ language });\n }\n}\n","import { switchPort } from '@cloudflare/containers';\nimport { createLogger, type LogContext, TraceContext } from '@repo/shared';\nimport { getSandbox, type Sandbox } from './sandbox';\nimport { sanitizeSandboxId, validatePort } from './security';\n\nexport interface SandboxEnv {\n Sandbox: DurableObjectNamespace<Sandbox>;\n}\n\nexport interface RouteInfo {\n port: number;\n sandboxId: string;\n path: string;\n token: string;\n}\n\nexport async function proxyToSandbox<E extends SandboxEnv>(\n request: Request,\n env: E\n): Promise<Response | null> {\n // Create logger context for this request\n const traceId =\n TraceContext.fromHeaders(request.headers) || TraceContext.generate();\n const logger = createLogger({\n component: 'sandbox-do',\n traceId,\n operation: 'proxy'\n });\n\n try {\n const url = new URL(request.url);\n const routeInfo = extractSandboxRoute(url);\n\n if (!routeInfo) {\n return null; // Not a request to an exposed container port\n }\n\n const { sandboxId, port, path, token } = routeInfo;\n // Preview URLs always use normalized (lowercase) IDs\n const sandbox = getSandbox(env.Sandbox, sandboxId, { normalizeId: true });\n\n // Critical security check: Validate token (mandatory for all user ports)\n // Skip check for control plane port 3000\n if (port !== 3000) {\n // Validate the token matches the port\n const isValidToken = await sandbox.validatePortToken(port, token);\n if (!isValidToken) {\n logger.warn('Invalid token access blocked', {\n port,\n sandboxId,\n path,\n hostname: url.hostname,\n url: request.url,\n method: request.method,\n userAgent: request.headers.get('User-Agent') || 'unknown'\n });\n\n return new Response(\n JSON.stringify({\n error: `Access denied: Invalid token or port not exposed`,\n code: 'INVALID_TOKEN'\n }),\n {\n status: 404,\n headers: {\n 'Content-Type': 'application/json'\n }\n }\n );\n }\n }\n\n // Detect WebSocket upgrade request\n const upgradeHeader = request.headers.get('Upgrade');\n if (upgradeHeader?.toLowerCase() === 'websocket') {\n // WebSocket path: Must use fetch() not containerFetch()\n // This bypasses JSRPC serialization boundary which cannot handle WebSocket upgrades\n return await sandbox.fetch(switchPort(request, port));\n }\n\n // Build proxy request with proper headers\n let proxyUrl: string;\n\n // Route based on the target port\n if (port !== 3000) {\n // Route directly to user's service on the specified port\n proxyUrl = `http://localhost:${port}${path}${url.search}`;\n } else {\n // Port 3000 is our control plane - route normally\n proxyUrl = `http://localhost:3000${path}${url.search}`;\n }\n\n const proxyRequest = new Request(proxyUrl, {\n method: request.method,\n headers: {\n ...Object.fromEntries(request.headers),\n 'X-Original-URL': request.url,\n 'X-Forwarded-Host': url.hostname,\n 'X-Forwarded-Proto': url.protocol.replace(':', ''),\n 'X-Sandbox-Name': sandboxId // Pass the friendly name\n },\n body: request.body,\n // @ts-expect-error - duplex required for body streaming in modern runtimes\n duplex: 'half'\n });\n\n return await sandbox.containerFetch(proxyRequest, port);\n } catch (error) {\n logger.error(\n 'Proxy routing error',\n error instanceof Error ? error : new Error(String(error))\n );\n return new Response('Proxy routing error', { status: 500 });\n }\n}\n\nfunction extractSandboxRoute(url: URL): RouteInfo | null {\n // Parse subdomain pattern: port-sandboxId-token.domain (tokens mandatory)\n // Token is always exactly 16 chars (generated by generatePortToken)\n const subdomainMatch = url.hostname.match(\n /^(\\d{4,5})-([^.-][^.]*?[^.-]|[^.-])-([a-z0-9_-]{16})\\.(.+)$/\n );\n\n if (!subdomainMatch) {\n return null;\n }\n\n const portStr = subdomainMatch[1];\n const sandboxId = subdomainMatch[2];\n const token = subdomainMatch[3]; // Mandatory token\n const domain = subdomainMatch[4];\n\n const port = parseInt(portStr, 10);\n if (!validatePort(port)) {\n return null;\n }\n\n let sanitizedSandboxId: string;\n try {\n sanitizedSandboxId = sanitizeSandboxId(sandboxId);\n } catch (error) {\n return null;\n }\n\n // DNS subdomain length limit is 63 characters\n if (sandboxId.length > 63) {\n return null;\n }\n\n return {\n port,\n sandboxId: sanitizedSandboxId,\n path: url.pathname || '/',\n token\n };\n}\n\nexport function isLocalhostPattern(hostname: string): boolean {\n // Handle IPv6 addresses in brackets (with or without port)\n if (hostname.startsWith('[')) {\n if (hostname.includes(']:')) {\n // [::1]:port format\n const ipv6Part = hostname.substring(0, hostname.indexOf(']:') + 1);\n return ipv6Part === '[::1]';\n } else {\n // [::1] format without port\n return hostname === '[::1]';\n }\n }\n\n // Handle bare IPv6 without brackets\n if (hostname === '::1') {\n return true;\n }\n\n // For IPv4 and regular hostnames, split on colon to remove port\n const hostPart = hostname.split(':')[0];\n\n return (\n hostPart === 'localhost' ||\n hostPart === '127.0.0.1' ||\n hostPart === '0.0.0.0'\n );\n}\n","/**\n * Server-Sent Events (SSE) parser for streaming responses\n * Converts ReadableStream<Uint8Array> to typed AsyncIterable<T>\n */\n\n/**\n * Parse a ReadableStream of SSE events into typed AsyncIterable\n * @param stream - The ReadableStream from fetch response\n * @param signal - Optional AbortSignal for cancellation\n */\nexport async function* parseSSEStream<T>(\n stream: ReadableStream<Uint8Array>,\n signal?: AbortSignal\n): AsyncIterable<T> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n // Check for cancellation\n if (signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n // Decode chunk and add to buffer\n buffer += decoder.decode(value, { stream: true });\n\n // Process complete SSE events in buffer\n const lines = buffer.split('\\n');\n\n // Keep the last incomplete line in buffer\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n // Skip empty lines\n if (line.trim() === '') continue;\n\n // Process SSE data lines\n if (line.startsWith('data: ')) {\n const data = line.substring(6);\n\n // Skip [DONE] markers or empty data\n if (data === '[DONE]' || data.trim() === '') continue;\n\n try {\n const event = JSON.parse(data) as T;\n yield event;\n } catch {\n // Skip invalid JSON events and continue processing\n }\n }\n // Handle other SSE fields if needed (event:, id:, retry:)\n // For now, we only care about data: lines\n }\n }\n\n // Process any remaining data in buffer\n if (buffer.trim() && buffer.startsWith('data: ')) {\n const data = buffer.substring(6);\n if (data !== '[DONE]' && data.trim()) {\n try {\n const event = JSON.parse(data) as T;\n yield event;\n } catch {\n // Skip invalid JSON in final event\n }\n }\n }\n } finally {\n // Clean up resources\n reader.releaseLock();\n }\n}\n\n/**\n * Helper to convert a Response with SSE stream directly to AsyncIterable\n * @param response - Response object with SSE stream\n * @param signal - Optional AbortSignal for cancellation\n */\nexport async function* responseToAsyncIterable<T>(\n response: Response,\n signal?: AbortSignal\n): AsyncIterable<T> {\n if (!response.ok) {\n throw new Error(\n `Response not ok: ${response.status} ${response.statusText}`\n );\n }\n\n if (!response.body) {\n throw new Error('No response body');\n }\n\n yield* parseSSEStream<T>(response.body, signal);\n}\n\n/**\n * Create an SSE-formatted ReadableStream from an AsyncIterable\n * (Useful for Worker endpoints that need to forward AsyncIterable as SSE)\n * @param events - AsyncIterable of events\n * @param options - Stream options\n */\nexport function asyncIterableToSSEStream<T>(\n events: AsyncIterable<T>,\n options?: {\n signal?: AbortSignal;\n serialize?: (event: T) => string;\n }\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n const serialize = options?.serialize || JSON.stringify;\n\n return new ReadableStream({\n async start(controller) {\n try {\n for await (const event of events) {\n if (options?.signal?.aborted) {\n controller.error(new Error('Operation was aborted'));\n break;\n }\n\n const data = serialize(event);\n const sseEvent = `data: ${data}\\n\\n`;\n controller.enqueue(encoder.encode(sseEvent));\n }\n\n // Send completion marker\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\n } catch (error) {\n controller.error(error);\n } finally {\n controller.close();\n }\n },\n\n cancel() {\n // Handle stream cancellation\n }\n });\n}\n","/**\n * Bucket mounting error classes\n *\n * These are SDK-side validation errors that follow the same pattern as SecurityError.\n * They are thrown before any container interaction occurs.\n */\n\nimport { ErrorCode } from '@repo/shared/errors';\n\n/**\n * Base error for bucket mounting operations\n */\nexport class BucketMountError extends Error {\n public readonly code: ErrorCode;\n\n constructor(message: string, code: ErrorCode = ErrorCode.BUCKET_MOUNT_ERROR) {\n super(message);\n this.name = 'BucketMountError';\n this.code = code;\n }\n}\n\n/**\n * Thrown when S3FS mount command fails\n */\nexport class S3FSMountError extends BucketMountError {\n constructor(message: string) {\n super(message, ErrorCode.S3FS_MOUNT_ERROR);\n this.name = 'S3FSMountError';\n }\n}\n\n/**\n * Thrown when no credentials found in environment\n */\nexport class MissingCredentialsError extends BucketMountError {\n constructor(message: string) {\n super(message, ErrorCode.MISSING_CREDENTIALS);\n this.name = 'MissingCredentialsError';\n }\n}\n\n/**\n * Thrown when bucket name, mount path, or options are invalid\n */\nexport class InvalidMountConfigError extends BucketMountError {\n constructor(message: string) {\n super(message, ErrorCode.INVALID_MOUNT_CONFIG);\n this.name = 'InvalidMountConfigError';\n }\n}\n","import type { BucketCredentials, MountBucketOptions } from '@repo/shared';\nimport { MissingCredentialsError } from './errors';\n\n/**\n * Detect credentials for bucket mounting from environment variables\n * Priority order:\n * 1. Explicit options.credentials\n * 2. Standard AWS env vars: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY\n * 3. Error: no credentials found\n *\n * @param options - Mount options\n * @param envVars - Environment variables\n * @returns Detected credentials\n * @throws MissingCredentialsError if no credentials found\n */\nexport function detectCredentials(\n options: MountBucketOptions,\n envVars: Record<string, string | undefined>\n): BucketCredentials {\n // Priority 1: Explicit credentials in options\n if (options.credentials) {\n return options.credentials;\n }\n\n // Priority 2: Standard AWS env vars\n const awsAccessKeyId = envVars.AWS_ACCESS_KEY_ID;\n const awsSecretAccessKey = envVars.AWS_SECRET_ACCESS_KEY;\n\n if (awsAccessKeyId && awsSecretAccessKey) {\n return {\n accessKeyId: awsAccessKeyId,\n secretAccessKey: awsSecretAccessKey\n };\n }\n\n // No credentials found - throw error with helpful message\n throw new MissingCredentialsError(\n `No credentials found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY ` +\n `environment variables, or pass explicit credentials in options.`\n );\n}\n","/**\n * Provider detection and s3fs flag configuration\n *\n * Based on s3fs-fuse documentation:\n * https://github.com/s3fs-fuse/s3fs-fuse/wiki/Non-Amazon-S3\n */\n\nimport type { BucketProvider } from '@repo/shared';\n\n/**\n * Detect provider from endpoint URL using pattern matching\n */\nexport function detectProviderFromUrl(endpoint: string): BucketProvider | null {\n try {\n const url = new URL(endpoint);\n const hostname = url.hostname.toLowerCase();\n\n if (hostname.endsWith('.r2.cloudflarestorage.com')) {\n return 'r2';\n }\n\n // Match AWS S3: *.amazonaws.com or s3.amazonaws.com\n if (\n hostname.endsWith('.amazonaws.com') ||\n hostname === 's3.amazonaws.com'\n ) {\n return 's3';\n }\n\n if (hostname === 'storage.googleapis.com') {\n return 'gcs';\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Get s3fs flags for a given provider\n *\n * Based on s3fs-fuse wiki recommendations:\n * https://github.com/s3fs-fuse/s3fs-fuse/wiki/Non-Amazon-S3\n */\nexport function getProviderFlags(provider: BucketProvider | null): string[] {\n if (!provider) {\n return ['use_path_request_style'];\n }\n\n switch (provider) {\n case 'r2':\n return ['nomixupload'];\n\n case 's3':\n return [];\n\n case 'gcs':\n return [];\n\n default:\n return ['use_path_request_style'];\n }\n}\n\n/**\n * Resolve s3fs options by combining provider defaults with user overrides\n */\nexport function resolveS3fsOptions(\n provider: BucketProvider | null,\n userOptions?: string[]\n): string[] {\n const providerFlags = getProviderFlags(provider);\n\n if (!userOptions || userOptions.length === 0) {\n return providerFlags;\n }\n\n // Merge provider flags with user options\n // User options take precedence (come last in the array)\n const allFlags = [...providerFlags, ...userOptions];\n\n // Deduplicate flags (keep last occurrence)\n const flagMap = new Map<string, string>();\n\n for (const flag of allFlags) {\n // Split on '=' to get the flag name\n const [flagName] = flag.split('=');\n flagMap.set(flagName, flag);\n }\n\n return Array.from(flagMap.values());\n}\n","/**\n * SDK version - automatically synchronized with package.json by Changesets\n * This file is auto-updated by .github/changeset-version.ts during releases\n * DO NOT EDIT MANUALLY - Changes will be overwritten on the next version bump\n */\nexport const SDK_VERSION = '0.5.4';\n","import { Container, getContainer, switchPort } from '@cloudflare/containers';\nimport type {\n BucketCredentials,\n BucketProvider,\n CodeContext,\n CreateContextOptions,\n ExecEvent,\n ExecOptions,\n ExecResult,\n ExecutionResult,\n ExecutionSession,\n ISandbox,\n MountBucketOptions,\n Process,\n ProcessOptions,\n ProcessStatus,\n RunCodeOptions,\n SandboxOptions,\n SessionOptions,\n StreamOptions\n} from '@repo/shared';\nimport {\n createLogger,\n getEnvString,\n type SessionDeleteResult,\n shellEscape,\n TraceContext\n} from '@repo/shared';\nimport { type ExecuteResponse, SandboxClient } from './clients';\nimport type { ErrorResponse } from './errors';\nimport { CustomDomainRequiredError, ErrorCode } from './errors';\nimport { CodeInterpreter } from './interpreter';\nimport { isLocalhostPattern } from './request-handler';\nimport { SecurityError, sanitizeSandboxId, validatePort } from './security';\nimport { parseSSEStream } from './sse-parser';\nimport {\n detectCredentials,\n detectProviderFromUrl,\n resolveS3fsOptions\n} from './storage-mount';\nimport {\n InvalidMountConfigError,\n S3FSMountError\n} from './storage-mount/errors';\nimport type { MountInfo } from './storage-mount/types';\nimport { SDK_VERSION } from './version';\n\nexport function getSandbox(\n ns: DurableObjectNamespace<Sandbox>,\n id: string,\n options?: SandboxOptions\n): Sandbox {\n const sanitizedId = sanitizeSandboxId(id);\n const effectiveId = options?.normalizeId\n ? sanitizedId.toLowerCase()\n : sanitizedId;\n\n const hasUppercase = /[A-Z]/.test(sanitizedId);\n if (!options?.normalizeId && hasUppercase) {\n const logger = createLogger({ component: 'sandbox-do' });\n logger.warn(\n `Sandbox ID \"${sanitizedId}\" contains uppercase letters, which causes issues with preview URLs (hostnames are case-insensitive). ` +\n `normalizeId will default to true in a future version to prevent this. ` +\n `Use lowercase IDs or pass { normalizeId: true } to prepare.`\n );\n }\n\n const stub = getContainer(ns, effectiveId) as unknown as Sandbox;\n\n stub.setSandboxName?.(effectiveId, options?.normalizeId);\n\n if (options?.baseUrl) {\n stub.setBaseUrl(options.baseUrl);\n }\n\n if (options?.sleepAfter !== undefined) {\n stub.setSleepAfter(options.sleepAfter);\n }\n\n if (options?.keepAlive !== undefined) {\n stub.setKeepAlive(options.keepAlive);\n }\n\n if (options?.containerTimeouts) {\n stub.setContainerTimeouts(options.containerTimeouts);\n }\n\n return Object.assign(stub, {\n wsConnect: connect(stub)\n });\n}\n\nexport function connect(stub: {\n fetch: (request: Request) => Promise<Response>;\n}) {\n return async (request: Request, port: number) => {\n if (!validatePort(port)) {\n throw new SecurityError(\n `Invalid or restricted port: ${port}. Ports must be in range 1024-65535 and not reserved.`\n );\n }\n const portSwitchedRequest = switchPort(request, port);\n return await stub.fetch(portSwitchedRequest);\n };\n}\n\nexport class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {\n defaultPort = 3000; // Default port for the container's Bun server\n sleepAfter: string | number = '10m'; // Sleep the sandbox if no requests are made in this timeframe\n\n client: SandboxClient;\n private codeInterpreter: CodeInterpreter;\n private sandboxName: string | null = null;\n private normalizeId: boolean = false;\n private baseUrl: string | null = null;\n private portTokens: Map<number, string> = new Map();\n private defaultSession: string | null = null;\n envVars: Record<string, string> = {};\n private logger: ReturnType<typeof createLogger>;\n private keepAliveEnabled: boolean = false;\n private activeMounts: Map<string, MountInfo> = new Map();\n\n /**\n * Default container startup timeouts (conservative for production)\n * Based on Cloudflare docs: \"Containers take several minutes to provision\"\n */\n private readonly DEFAULT_CONTAINER_TIMEOUTS = {\n // Time to get container instance and launch VM\n // @cloudflare/containers default: 8s (too short for cold starts)\n instanceGetTimeoutMS: 30_000, // 30 seconds\n\n // Time for application to start and ports to be ready\n // @cloudflare/containers default: 20s\n portReadyTimeoutMS: 90_000, // 90 seconds (allows for heavy containers)\n\n // Polling interval for checking container readiness\n // @cloudflare/containers default: 300ms (too aggressive)\n waitIntervalMS: 1000 // 1 second (reduces load)\n };\n\n /**\n * Active container timeout configuration\n * Can be set via options, env vars, or defaults\n */\n private containerTimeouts = { ...this.DEFAULT_CONTAINER_TIMEOUTS };\n\n constructor(ctx: DurableObjectState<{}>, env: Env) {\n super(ctx, env);\n\n const envObj = env as Record<string, unknown>;\n // Set sandbox environment variables from env object\n const sandboxEnvKeys = ['SANDBOX_LOG_LEVEL', 'SANDBOX_LOG_FORMAT'] as const;\n sandboxEnvKeys.forEach((key) => {\n if (envObj?.[key]) {\n this.envVars[key] = String(envObj[key]);\n }\n });\n\n // Initialize timeouts with env var fallbacks\n this.containerTimeouts = this.getDefaultTimeouts(envObj);\n\n this.logger = createLogger({\n component: 'sandbox-do',\n sandboxId: this.ctx.id.toString()\n });\n\n this.client = new SandboxClient({\n logger: this.logger,\n port: 3000, // Control plane port\n stub: this\n });\n\n // Initialize code interpreter - pass 'this' after client is ready\n // The CodeInterpreter extracts client.interpreter from the sandbox\n this.codeInterpreter = new CodeInterpreter(this);\n\n this.ctx.blockConcurrencyWhile(async () => {\n this.sandboxName =\n (await this.ctx.storage.get<string>('sandboxName')) || null;\n this.normalizeId =\n (await this.ctx.storage.get<boolean>('normalizeId')) || false;\n this.defaultSession =\n (await this.ctx.storage.get<string>('defaultSession')) || null;\n const storedTokens =\n (await this.ctx.storage.get<Record<string, string>>('portTokens')) ||\n {};\n\n // Convert stored tokens back to Map\n this.portTokens = new Map();\n for (const [portStr, token] of Object.entries(storedTokens)) {\n this.portTokens.set(parseInt(portStr, 10), token);\n }\n\n // Load saved timeout configuration (highest priority)\n const storedTimeouts =\n await this.ctx.storage.get<\n NonNullable<SandboxOptions['containerTimeouts']>\n >('containerTimeouts');\n if (storedTimeouts) {\n this.containerTimeouts = {\n ...this.containerTimeouts,\n ...storedTimeouts\n };\n }\n });\n }\n\n async setSandboxName(name: string, normalizeId?: boolean): Promise<void> {\n if (!this.sandboxName) {\n this.sandboxName = name;\n this.normalizeId = normalizeId || false;\n await this.ctx.storage.put('sandboxName', name);\n await this.ctx.storage.put('normalizeId', this.normalizeId);\n }\n }\n\n // RPC method to set the base URL\n async setBaseUrl(baseUrl: string): Promise<void> {\n if (!this.baseUrl) {\n this.baseUrl = baseUrl;\n await this.ctx.storage.put('baseUrl', baseUrl);\n } else {\n if (this.baseUrl !== baseUrl) {\n throw new Error(\n 'Base URL already set and different from one previously provided'\n );\n }\n }\n }\n\n // RPC method to set the sleep timeout\n async setSleepAfter(sleepAfter: string | number): Promise<void> {\n this.sleepAfter = sleepAfter;\n }\n\n // RPC method to enable keepAlive mode\n async setKeepAlive(keepAlive: boolean): Promise<void> {\n this.keepAliveEnabled = keepAlive;\n if (keepAlive) {\n this.logger.info(\n 'KeepAlive mode enabled - container will stay alive until explicitly destroyed'\n );\n } else {\n this.logger.info(\n 'KeepAlive mode disabled - container will timeout normally'\n );\n }\n }\n\n // RPC method to set environment variables\n async setEnvVars(envVars: Record<string, string>): Promise<void> {\n // Update local state for new sessions\n this.envVars = { ...this.envVars, ...envVars };\n\n // If default session already exists, update it directly\n if (this.defaultSession) {\n // Set environment variables by executing export commands in the existing session\n for (const [key, value] of Object.entries(envVars)) {\n const escapedValue = value.replace(/'/g, \"'\\\\''\");\n const exportCommand = `export ${key}='${escapedValue}'`;\n\n const result = await this.client.commands.execute(\n exportCommand,\n this.defaultSession\n );\n\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to set ${key}: ${result.stderr || 'Unknown error'}`\n );\n }\n }\n }\n }\n\n /**\n * RPC method to configure container startup timeouts\n */\n async setContainerTimeouts(\n timeouts: NonNullable<SandboxOptions['containerTimeouts']>\n ): Promise<void> {\n const validated = { ...this.containerTimeouts };\n\n // Validate each timeout if provided\n if (timeouts.instanceGetTimeoutMS !== undefined) {\n validated.instanceGetTimeoutMS = this.validateTimeout(\n timeouts.instanceGetTimeoutMS,\n 'instanceGetTimeoutMS',\n 5_000,\n 300_000\n );\n }\n\n if (timeouts.portReadyTimeoutMS !== undefined) {\n validated.portReadyTimeoutMS = this.validateTimeout(\n timeouts.portReadyTimeoutMS,\n 'portReadyTimeoutMS',\n 10_000,\n 600_000\n );\n }\n\n if (timeouts.waitIntervalMS !== undefined) {\n validated.waitIntervalMS = this.validateTimeout(\n timeouts.waitIntervalMS,\n 'waitIntervalMS',\n 100,\n 5_000\n );\n }\n\n this.containerTimeouts = validated;\n\n // Persist to storage\n await this.ctx.storage.put('containerTimeouts', this.containerTimeouts);\n\n this.logger.debug('Container timeouts updated', this.containerTimeouts);\n }\n\n /**\n * Validate a timeout value is within acceptable range\n * Throws error if invalid - used for user-provided values\n */\n private validateTimeout(\n value: number,\n name: string,\n min: number,\n max: number\n ): number {\n if (\n typeof value !== 'number' ||\n Number.isNaN(value) ||\n !Number.isFinite(value)\n ) {\n throw new Error(`${name} must be a valid finite number, got ${value}`);\n }\n\n if (value < min || value > max) {\n throw new Error(\n `${name} must be between ${min}-${max}ms, got ${value}ms`\n );\n }\n\n return value;\n }\n\n /**\n * Get default timeouts with env var fallbacks and validation\n * Precedence: SDK defaults < Env vars < User config\n */\n private getDefaultTimeouts(\n env: Record<string, unknown>\n ): typeof this.DEFAULT_CONTAINER_TIMEOUTS {\n const parseAndValidate = (\n envVar: string | undefined,\n name: keyof typeof this.DEFAULT_CONTAINER_TIMEOUTS,\n min: number,\n max: number\n ): number => {\n const defaultValue = this.DEFAULT_CONTAINER_TIMEOUTS[name];\n\n if (envVar === undefined) {\n return defaultValue;\n }\n\n const parsed = parseInt(envVar, 10);\n\n if (Number.isNaN(parsed)) {\n this.logger.warn(\n `Invalid ${name}: \"${envVar}\" is not a number. Using default: ${defaultValue}ms`\n );\n return defaultValue;\n }\n\n if (parsed < min || parsed > max) {\n this.logger.warn(\n `Invalid ${name}: ${parsed}ms. Must be ${min}-${max}ms. Using default: ${defaultValue}ms`\n );\n return defaultValue;\n }\n\n return parsed;\n };\n\n return {\n instanceGetTimeoutMS: parseAndValidate(\n getEnvString(env, 'SANDBOX_INSTANCE_TIMEOUT_MS'),\n 'instanceGetTimeoutMS',\n 5_000, // Min 5s\n 300_000 // Max 5min\n ),\n portReadyTimeoutMS: parseAndValidate(\n getEnvString(env, 'SANDBOX_PORT_TIMEOUT_MS'),\n 'portReadyTimeoutMS',\n 10_000, // Min 10s\n 600_000 // Max 10min\n ),\n waitIntervalMS: parseAndValidate(\n getEnvString(env, 'SANDBOX_POLL_INTERVAL_MS'),\n 'waitIntervalMS',\n 100, // Min 100ms\n 5_000 // Max 5s\n )\n };\n }\n\n /*\n * Mount an S3-compatible bucket as a local directory using S3FS-FUSE\n *\n * Requires explicit endpoint URL. Credentials are auto-detected from environment\n * variables or can be provided explicitly.\n *\n * @param bucket - Bucket name\n * @param mountPath - Absolute path in container to mount at\n * @param options - Configuration options with required endpoint\n * @throws MissingCredentialsError if no credentials found in environment\n * @throws S3FSMountError if S3FS mount command fails\n * @throws InvalidMountConfigError if bucket name, mount path, or endpoint is invalid\n */\n async mountBucket(\n bucket: string,\n mountPath: string,\n options: MountBucketOptions\n ): Promise<void> {\n this.logger.info(`Mounting bucket ${bucket} to ${mountPath}`);\n\n // Validate options\n this.validateMountOptions(bucket, mountPath, options);\n\n // Detect provider from explicit option or URL pattern\n const provider: BucketProvider | null =\n options.provider || detectProviderFromUrl(options.endpoint);\n\n this.logger.debug(`Detected provider: ${provider || 'unknown'}`, {\n explicitProvider: options.provider\n });\n\n // Detect credentials\n const credentials = detectCredentials(options, this.envVars);\n\n // Generate unique password file path\n const passwordFilePath = this.generatePasswordFilePath();\n\n // Reserve mount path immediately to prevent race conditions\n // (two concurrent mount calls would both pass validation otherwise)\n this.activeMounts.set(mountPath, {\n bucket,\n mountPath,\n endpoint: options.endpoint,\n provider,\n passwordFilePath,\n mounted: false\n });\n\n try {\n // Create password file with credentials\n await this.createPasswordFile(passwordFilePath, bucket, credentials);\n\n // Create mount directory\n await this.exec(`mkdir -p ${shellEscape(mountPath)}`);\n\n // Execute S3FS mount with password file\n await this.executeS3FSMount(\n bucket,\n mountPath,\n options,\n provider,\n passwordFilePath\n );\n\n // Mark as successfully mounted\n this.activeMounts.set(mountPath, {\n bucket,\n mountPath,\n endpoint: options.endpoint,\n provider,\n passwordFilePath,\n mounted: true\n });\n\n this.logger.info(`Successfully mounted bucket ${bucket} to ${mountPath}`);\n } catch (error) {\n // Clean up password file on failure\n await this.deletePasswordFile(passwordFilePath);\n\n // Clean up reservation on failure\n this.activeMounts.delete(mountPath);\n throw error;\n }\n }\n\n /**\n * Manually unmount a bucket filesystem\n *\n * @param mountPath - Absolute path where the bucket is mounted\n * @throws InvalidMountConfigError if mount path doesn't exist or isn't mounted\n */\n async unmountBucket(mountPath: string): Promise<void> {\n this.logger.info(`Unmounting bucket from ${mountPath}`);\n\n // Look up mount by path\n const mountInfo = this.activeMounts.get(mountPath);\n\n // Throw error if mount doesn't exist\n if (!mountInfo) {\n throw new InvalidMountConfigError(\n `No active mount found at path: ${mountPath}`\n );\n }\n\n // Unmount the filesystem\n try {\n await this.exec(`fusermount -u ${shellEscape(mountPath)}`);\n mountInfo.mounted = false;\n\n // Only remove from tracking if unmount succeeded\n this.activeMounts.delete(mountPath);\n } finally {\n // Always cleanup password file, even if unmount fails\n await this.deletePasswordFile(mountInfo.passwordFilePath);\n }\n\n this.logger.info(`Successfully unmounted bucket from ${mountPath}`);\n }\n\n /**\n * Validate mount options\n */\n private validateMountOptions(\n bucket: string,\n mountPath: string,\n options: MountBucketOptions\n ): void {\n // Require endpoint field\n if (!options.endpoint) {\n throw new InvalidMountConfigError(\n 'Endpoint is required. Provide the full S3-compatible endpoint URL.'\n );\n }\n\n // Basic URL validation\n try {\n new URL(options.endpoint);\n } catch (error) {\n throw new InvalidMountConfigError(\n `Invalid endpoint URL: \"${options.endpoint}\". Must be a valid HTTP(S) URL.`\n );\n }\n\n // Validate bucket name (S3-compatible naming rules)\n const bucketNameRegex = /^[a-z0-9]([a-z0-9.-]{0,61}[a-z0-9])?$/;\n if (!bucketNameRegex.test(bucket)) {\n throw new InvalidMountConfigError(\n `Invalid bucket name: \"${bucket}\". Bucket names must be 3-63 characters, ` +\n `lowercase alphanumeric, dots, or hyphens, and cannot start/end with dots or hyphens.`\n );\n }\n\n // Validate mount path is absolute\n if (!mountPath.startsWith('/')) {\n throw new InvalidMountConfigError(\n `Mount path must be absolute (start with /): \"${mountPath}\"`\n );\n }\n\n // Check for duplicate mount path\n if (this.activeMounts.has(mountPath)) {\n const existingMount = this.activeMounts.get(mountPath);\n throw new InvalidMountConfigError(\n `Mount path \"${mountPath}\" is already in use by bucket \"${existingMount?.bucket}\". ` +\n `Unmount the existing bucket first or use a different mount path.`\n );\n }\n }\n\n /**\n * Generate unique password file path for s3fs credentials\n */\n private generatePasswordFilePath(): string {\n const uuid = crypto.randomUUID();\n return `/tmp/.passwd-s3fs-${uuid}`;\n }\n\n /**\n * Create password file with s3fs credentials\n * Format: bucket:accessKeyId:secretAccessKey\n */\n private async createPasswordFile(\n passwordFilePath: string,\n bucket: string,\n credentials: BucketCredentials\n ): Promise<void> {\n const content = `${bucket}:${credentials.accessKeyId}:${credentials.secretAccessKey}`;\n\n await this.writeFile(passwordFilePath, content);\n\n await this.exec(`chmod 0600 ${shellEscape(passwordFilePath)}`);\n\n this.logger.debug(`Created password file: ${passwordFilePath}`);\n }\n\n /**\n * Delete password file\n */\n private async deletePasswordFile(passwordFilePath: string): Promise<void> {\n try {\n await this.exec(`rm -f ${shellEscape(passwordFilePath)}`);\n this.logger.debug(`Deleted password file: ${passwordFilePath}`);\n } catch (error) {\n this.logger.warn(`Failed to delete password file ${passwordFilePath}`, {\n error: error instanceof Error ? error.message : String(error)\n });\n }\n }\n\n /**\n * Execute S3FS mount command\n */\n private async executeS3FSMount(\n bucket: string,\n mountPath: string,\n options: MountBucketOptions,\n provider: BucketProvider | null,\n passwordFilePath: string\n ): Promise<void> {\n // Resolve s3fs options (provider defaults + user overrides)\n const resolvedOptions = resolveS3fsOptions(provider, options.s3fsOptions);\n\n // Build s3fs mount command\n const s3fsArgs: string[] = [];\n\n // Add password file option FIRST\n s3fsArgs.push(`passwd_file=${passwordFilePath}`);\n\n // Add resolved provider-specific and user options\n s3fsArgs.push(...resolvedOptions);\n\n // Add read-only flag if requested\n if (options.readOnly) {\n s3fsArgs.push('ro');\n }\n\n // Add endpoint URL\n s3fsArgs.push(`url=${options.endpoint}`);\n\n // Build final command with escaped options\n const optionsStr = shellEscape(s3fsArgs.join(','));\n const mountCmd = `s3fs ${shellEscape(bucket)} ${shellEscape(mountPath)} -o ${optionsStr}`;\n\n this.logger.debug('Executing s3fs mount', {\n bucket,\n mountPath,\n provider,\n resolvedOptions\n });\n\n // Execute mount command\n const result = await this.exec(mountCmd);\n\n if (result.exitCode !== 0) {\n throw new S3FSMountError(\n `S3FS mount failed: ${result.stderr || result.stdout || 'Unknown error'}`\n );\n }\n\n this.logger.debug('Mount command executed successfully');\n }\n\n /**\n * Cleanup and destroy the sandbox container\n */\n override async destroy(): Promise<void> {\n this.logger.info('Destroying sandbox container');\n\n // Unmount all mounted buckets and cleanup password files\n for (const [mountPath, mountInfo] of this.activeMounts.entries()) {\n if (mountInfo.mounted) {\n try {\n this.logger.info(\n `Unmounting bucket ${mountInfo.bucket} from ${mountPath}`\n );\n await this.exec(`fusermount -u ${shellEscape(mountPath)}`);\n mountInfo.mounted = false;\n } catch (error) {\n const errorMsg =\n error instanceof Error ? error.message : String(error);\n this.logger.warn(\n `Failed to unmount bucket ${mountInfo.bucket} from ${mountPath}: ${errorMsg}`\n );\n }\n }\n\n // Always cleanup password file\n await this.deletePasswordFile(mountInfo.passwordFilePath);\n }\n\n await super.destroy();\n }\n\n override onStart() {\n this.logger.debug('Sandbox started');\n\n // Check version compatibility asynchronously (don't block startup)\n this.checkVersionCompatibility().catch((error) => {\n this.logger.error(\n 'Version compatibility check failed',\n error instanceof Error ? error : new Error(String(error))\n );\n });\n }\n\n /**\n * Check if the container version matches the SDK version\n * Logs a warning if there's a mismatch\n */\n private async checkVersionCompatibility(): Promise<void> {\n try {\n // Get the SDK version (imported from version.ts)\n const sdkVersion = SDK_VERSION;\n\n // Get container version\n const containerVersion = await this.client.utils.getVersion();\n\n // If container version is unknown, it's likely an old container without the endpoint\n if (containerVersion === 'unknown') {\n this.logger.warn(\n 'Container version check: Container version could not be determined. ' +\n 'This may indicate an outdated container image. ' +\n 'Please update your container to match SDK version ' +\n sdkVersion\n );\n return;\n }\n\n // Check if versions match\n if (containerVersion !== sdkVersion) {\n const message =\n `Version mismatch detected! SDK version (${sdkVersion}) does not match ` +\n `container version (${containerVersion}). This may cause compatibility issues. ` +\n `Please update your container image to version ${sdkVersion}`;\n\n // Log warning - we can't reliably detect dev vs prod environment in Durable Objects\n // so we always use warning level as requested by the user\n this.logger.warn(message);\n } else {\n this.logger.debug('Version check passed', {\n sdkVersion,\n containerVersion\n });\n }\n } catch (error) {\n // Don't fail the sandbox initialization if version check fails\n this.logger.debug('Version compatibility check encountered an error', {\n error: error instanceof Error ? error.message : String(error)\n });\n }\n }\n\n override async onStop() {\n this.logger.debug('Sandbox stopped');\n\n // Clear in-memory state that references the old container\n // This prevents stale references after container restarts\n this.portTokens.clear();\n this.defaultSession = null;\n this.activeMounts.clear();\n\n // Persist cleanup to storage so state is clean on next container start\n await Promise.all([\n this.ctx.storage.delete('portTokens'),\n this.ctx.storage.delete('defaultSession')\n ]);\n }\n\n override onError(error: unknown) {\n this.logger.error(\n 'Sandbox error',\n error instanceof Error ? error : new Error(String(error))\n );\n }\n\n /**\n * Override Container.containerFetch to use production-friendly timeouts\n * Automatically starts container with longer timeouts if not running\n */\n override async containerFetch(\n requestOrUrl: Request | string | URL,\n portOrInit?: number | RequestInit,\n portParam?: number\n ): Promise<Response> {\n // Parse arguments to extract request and port\n const { request, port } = this.parseContainerFetchArgs(\n requestOrUrl,\n portOrInit,\n portParam\n );\n\n const state = await this.getState();\n\n // If container not healthy, start it with production timeouts\n if (state.status !== 'healthy') {\n try {\n this.logger.debug('Starting container with configured timeouts', {\n instanceTimeout: this.containerTimeouts.instanceGetTimeoutMS,\n portTimeout: this.containerTimeouts.portReadyTimeoutMS\n });\n\n await this.startAndWaitForPorts({\n ports: port,\n cancellationOptions: {\n instanceGetTimeoutMS: this.containerTimeouts.instanceGetTimeoutMS,\n portReadyTimeoutMS: this.containerTimeouts.portReadyTimeoutMS,\n waitInterval: this.containerTimeouts.waitIntervalMS,\n abort: request.signal\n }\n });\n } catch (e) {\n // Handle provisioning vs startup errors\n if (this.isNoInstanceError(e)) {\n return new Response(\n 'Container is currently provisioning. This can take several minutes on first deployment. Please retry in a moment.',\n {\n status: 503,\n headers: { 'Retry-After': '10' } // Suggest 10s retry\n }\n );\n }\n\n // Other startup errors\n this.logger.error(\n 'Container startup failed',\n e instanceof Error ? e : new Error(String(e))\n );\n return new Response(\n `Failed to start container: ${e instanceof Error ? e.message : String(e)}`,\n { status: 500 }\n );\n }\n }\n\n // Delegate to parent for the actual fetch (handles TCP port access internally)\n return await super.containerFetch(requestOrUrl, portOrInit, portParam);\n }\n\n /**\n * Helper: Check if error is \"no container instance available\"\n */\n private isNoInstanceError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.toLowerCase().includes('no container instance')\n );\n }\n\n /**\n * Helper: Parse containerFetch arguments (supports multiple signatures)\n */\n private parseContainerFetchArgs(\n requestOrUrl: Request | string | URL,\n portOrInit?: number | RequestInit,\n portParam?: number\n ): { request: Request; port: number } {\n let request: Request;\n let port: number | undefined;\n\n if (requestOrUrl instanceof Request) {\n request = requestOrUrl;\n port = typeof portOrInit === 'number' ? portOrInit : undefined;\n } else {\n const url =\n typeof requestOrUrl === 'string'\n ? requestOrUrl\n : requestOrUrl.toString();\n const init = typeof portOrInit === 'number' ? {} : portOrInit || {};\n port =\n typeof portOrInit === 'number'\n ? portOrInit\n : typeof portParam === 'number'\n ? portParam\n : undefined;\n request = new Request(url, init);\n }\n\n port ??= this.defaultPort;\n\n if (port === undefined) {\n throw new Error('No port specified for container fetch');\n }\n\n return { request, port };\n }\n\n /**\n * Override onActivityExpired to prevent automatic shutdown when keepAlive is enabled\n * When keepAlive is disabled, calls parent implementation which stops the container\n */\n override async onActivityExpired(): Promise<void> {\n if (this.keepAliveEnabled) {\n this.logger.debug(\n 'Activity expired but keepAlive is enabled - container will stay alive'\n );\n // Do nothing - don't call stop(), container stays alive\n } else {\n // Default behavior: stop the container\n this.logger.debug('Activity expired - stopping container');\n await super.onActivityExpired();\n }\n }\n\n // Override fetch to route internal container requests to appropriate ports\n override async fetch(request: Request): Promise<Response> {\n // Extract or generate trace ID from request\n const traceId =\n TraceContext.fromHeaders(request.headers) || TraceContext.generate();\n\n // Create request-specific logger with trace ID\n const requestLogger = this.logger.child({ traceId, operation: 'fetch' });\n\n const url = new URL(request.url);\n\n // Capture and store the sandbox name from the header if present\n if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {\n const name = request.headers.get('X-Sandbox-Name')!;\n this.sandboxName = name;\n await this.ctx.storage.put('sandboxName', name);\n }\n\n // Detect WebSocket upgrade request (RFC 6455 compliant)\n const upgradeHeader = request.headers.get('Upgrade');\n const connectionHeader = request.headers.get('Connection');\n const isWebSocket =\n upgradeHeader?.toLowerCase() === 'websocket' &&\n connectionHeader?.toLowerCase().includes('upgrade');\n\n if (isWebSocket) {\n // WebSocket path: Let parent Container class handle WebSocket proxying\n // This bypasses containerFetch() which uses JSRPC and cannot handle WebSocket upgrades\n try {\n requestLogger.debug('WebSocket upgrade requested', {\n path: url.pathname,\n port: this.determinePort(url)\n });\n return await super.fetch(request);\n } catch (error) {\n requestLogger.error(\n 'WebSocket connection failed',\n error instanceof Error ? error : new Error(String(error)),\n { path: url.pathname }\n );\n throw error;\n }\n }\n\n // Non-WebSocket: Use existing port determination and HTTP routing logic\n const port = this.determinePort(url);\n\n // Route to the appropriate port\n return await this.containerFetch(request, port);\n }\n\n wsConnect(request: Request, port: number): Promise<Response> {\n // Dummy implementation that will be overridden by the stub\n throw new Error('Not implemented here to avoid RPC serialization issues');\n }\n\n private determinePort(url: URL): number {\n // Extract port from proxy requests (e.g., /proxy/8080/*)\n const proxyMatch = url.pathname.match(/^\\/proxy\\/(\\d+)/);\n if (proxyMatch) {\n return parseInt(proxyMatch[1], 10);\n }\n\n // All other requests go to control plane on port 3000\n // This includes /api/* endpoints and any other control requests\n return 3000;\n }\n\n /**\n * Ensure default session exists - lazy initialization\n * This is called automatically by all public methods that need a session\n *\n * The session is persisted to Durable Object storage to survive hot reloads\n * during development. If a session already exists in the container after reload,\n * we reuse it instead of trying to create a new one.\n */\n private async ensureDefaultSession(): Promise<string> {\n if (!this.defaultSession) {\n const sessionId = `sandbox-${this.sandboxName || 'default'}`;\n\n try {\n // Try to create session in container\n await this.client.utils.createSession({\n id: sessionId,\n env: this.envVars || {},\n cwd: '/workspace'\n });\n\n this.defaultSession = sessionId;\n // Persist to storage so it survives hot reloads\n await this.ctx.storage.put('defaultSession', sessionId);\n this.logger.debug('Default session initialized', { sessionId });\n } catch (error: unknown) {\n // If session already exists (e.g., after hot reload), reuse it\n if (\n error instanceof Error &&\n error.message.includes('already exists')\n ) {\n this.logger.debug('Reusing existing session after reload', {\n sessionId\n });\n this.defaultSession = sessionId;\n // Persist to storage in case it wasn't saved before\n await this.ctx.storage.put('defaultSession', sessionId);\n } else {\n // Re-throw other errors\n throw error;\n }\n }\n }\n return this.defaultSession;\n }\n\n // Enhanced exec method - always returns ExecResult with optional streaming\n // This replaces the old exec method to match ISandbox interface\n async exec(command: string, options?: ExecOptions): Promise<ExecResult> {\n const session = await this.ensureDefaultSession();\n return this.execWithSession(command, session, options);\n }\n\n /**\n * Internal session-aware exec implementation\n * Used by both public exec() and session wrappers\n */\n private async execWithSession(\n command: string,\n sessionId: string,\n options?: ExecOptions\n ): Promise<ExecResult> {\n const startTime = Date.now();\n const timestamp = new Date().toISOString();\n\n let timeoutId: NodeJS.Timeout | undefined;\n\n try {\n // Handle cancellation\n if (options?.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n let result: ExecResult;\n\n if (options?.stream && options?.onOutput) {\n // Streaming with callbacks - we need to collect the final result\n result = await this.executeWithStreaming(\n command,\n sessionId,\n options,\n startTime,\n timestamp\n );\n } else {\n // Regular execution with session\n const commandOptions =\n options &&\n (options.timeout !== undefined ||\n options.env !== undefined ||\n options.cwd !== undefined)\n ? {\n timeoutMs: options.timeout,\n env: options.env,\n cwd: options.cwd\n }\n : undefined;\n\n const response = await this.client.commands.execute(\n command,\n sessionId,\n commandOptions\n );\n\n const duration = Date.now() - startTime;\n result = this.mapExecuteResponseToExecResult(\n response,\n duration,\n sessionId\n );\n }\n\n // Call completion callback if provided\n if (options?.onComplete) {\n options.onComplete(result);\n }\n\n return result;\n } catch (error) {\n if (options?.onError && error instanceof Error) {\n options.onError(error);\n }\n throw error;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n\n private async executeWithStreaming(\n command: string,\n sessionId: string,\n options: ExecOptions,\n startTime: number,\n timestamp: string\n ): Promise<ExecResult> {\n let stdout = '';\n let stderr = '';\n\n try {\n const stream = await this.client.commands.executeStream(\n command,\n sessionId,\n {\n timeoutMs: options.timeout,\n env: options.env,\n cwd: options.cwd\n }\n );\n\n for await (const event of parseSSEStream<ExecEvent>(stream)) {\n // Check for cancellation\n if (options.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n switch (event.type) {\n case 'stdout':\n case 'stderr':\n if (event.data) {\n // Update accumulated output\n if (event.type === 'stdout') stdout += event.data;\n if (event.type === 'stderr') stderr += event.data;\n\n // Call user's callback\n if (options.onOutput) {\n options.onOutput(event.type, event.data);\n }\n }\n break;\n\n case 'complete': {\n // Use result from complete event if available\n const duration = Date.now() - startTime;\n return {\n success: (event.exitCode ?? 0) === 0,\n exitCode: event.exitCode ?? 0,\n stdout,\n stderr,\n command,\n duration,\n timestamp,\n sessionId\n };\n }\n\n case 'error':\n throw new Error(event.data || 'Command execution failed');\n }\n }\n\n // If we get here without a complete event, something went wrong\n throw new Error('Stream ended without completion event');\n } catch (error) {\n if (options.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n throw error;\n }\n }\n\n private mapExecuteResponseToExecResult(\n response: ExecuteResponse,\n duration: number,\n sessionId?: string\n ): ExecResult {\n return {\n success: response.success,\n exitCode: response.exitCode,\n stdout: response.stdout,\n stderr: response.stderr,\n command: response.command,\n duration,\n timestamp: response.timestamp,\n sessionId\n };\n }\n\n /**\n * Create a Process domain object from HTTP client DTO\n * Centralizes process object creation with bound methods\n * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers\n */\n private createProcessFromDTO(\n data: {\n id: string;\n pid?: number;\n command: string;\n status: ProcessStatus;\n startTime: string | Date;\n endTime?: string | Date;\n exitCode?: number;\n },\n sessionId: string\n ): Process {\n return {\n id: data.id,\n pid: data.pid,\n command: data.command,\n status: data.status,\n startTime:\n typeof data.startTime === 'string'\n ? new Date(data.startTime)\n : data.startTime,\n endTime: data.endTime\n ? typeof data.endTime === 'string'\n ? new Date(data.endTime)\n : data.endTime\n : undefined,\n exitCode: data.exitCode,\n sessionId,\n\n kill: async (signal?: string) => {\n await this.killProcess(data.id, signal);\n },\n\n getStatus: async () => {\n const current = await this.getProcess(data.id);\n return current?.status || 'error';\n },\n\n getLogs: async () => {\n const logs = await this.getProcessLogs(data.id);\n return { stdout: logs.stdout, stderr: logs.stderr };\n }\n };\n }\n\n // Background process management\n async startProcess(\n command: string,\n options?: ProcessOptions,\n sessionId?: string\n ): Promise<Process> {\n // Use the new HttpClient method to start the process\n try {\n const session = sessionId ?? (await this.ensureDefaultSession());\n const requestOptions = {\n ...(options?.processId !== undefined && {\n processId: options.processId\n }),\n ...(options?.timeout !== undefined && { timeoutMs: options.timeout }),\n ...(options?.env !== undefined && { env: options.env }),\n ...(options?.cwd !== undefined && { cwd: options.cwd }),\n ...(options?.encoding !== undefined && { encoding: options.encoding }),\n ...(options?.autoCleanup !== undefined && {\n autoCleanup: options.autoCleanup\n })\n };\n\n const response = await this.client.processes.startProcess(\n command,\n session,\n requestOptions\n );\n\n const processObj = this.createProcessFromDTO(\n {\n id: response.processId,\n pid: response.pid,\n command: response.command,\n status: 'running' as ProcessStatus,\n startTime: new Date(),\n endTime: undefined,\n exitCode: undefined\n },\n session\n );\n\n // Call onStart callback if provided\n if (options?.onStart) {\n options.onStart(processObj);\n }\n\n return processObj;\n } catch (error) {\n if (options?.onError && error instanceof Error) {\n options.onError(error);\n }\n\n throw error;\n }\n }\n\n async listProcesses(sessionId?: string): Promise<Process[]> {\n const session = sessionId ?? (await this.ensureDefaultSession());\n const response = await this.client.processes.listProcesses();\n\n return response.processes.map((processData) =>\n this.createProcessFromDTO(\n {\n id: processData.id,\n pid: processData.pid,\n command: processData.command,\n status: processData.status,\n startTime: processData.startTime,\n endTime: processData.endTime,\n exitCode: processData.exitCode\n },\n session\n )\n );\n }\n\n async getProcess(id: string, sessionId?: string): Promise<Process | null> {\n const session = sessionId ?? (await this.ensureDefaultSession());\n const response = await this.client.processes.getProcess(id);\n if (!response.process) {\n return null;\n }\n\n const processData = response.process;\n return this.createProcessFromDTO(\n {\n id: processData.id,\n pid: processData.pid,\n command: processData.command,\n status: processData.status,\n startTime: processData.startTime,\n endTime: processData.endTime,\n exitCode: processData.exitCode\n },\n session\n );\n }\n\n async killProcess(\n id: string,\n signal?: string,\n sessionId?: string\n ): Promise<void> {\n // Note: signal parameter is not currently supported by the HttpClient implementation\n // The HTTP client already throws properly typed errors, so we just let them propagate\n await this.client.processes.killProcess(id);\n }\n\n async killAllProcesses(sessionId?: string): Promise<number> {\n const response = await this.client.processes.killAllProcesses();\n return response.cleanedCount;\n }\n\n async cleanupCompletedProcesses(sessionId?: string): Promise<number> {\n // For now, this would need to be implemented as a container endpoint\n // as we no longer maintain local process storage\n // We'll return 0 as a placeholder until the container endpoint is added\n return 0;\n }\n\n async getProcessLogs(\n id: string,\n sessionId?: string\n ): Promise<{ stdout: string; stderr: string; processId: string }> {\n // The HTTP client already throws properly typed errors, so we just let them propagate\n const response = await this.client.processes.getProcessLogs(id);\n return {\n stdout: response.stdout,\n stderr: response.stderr,\n processId: response.processId\n };\n }\n\n // Streaming methods - return ReadableStream for RPC compatibility\n async execStream(\n command: string,\n options?: StreamOptions\n ): Promise<ReadableStream<Uint8Array>> {\n // Check for cancellation\n if (options?.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n const session = await this.ensureDefaultSession();\n // Get the stream from CommandClient\n return this.client.commands.executeStream(command, session, {\n timeoutMs: options?.timeout,\n env: options?.env,\n cwd: options?.cwd\n });\n }\n\n /**\n * Internal session-aware execStream implementation\n */\n private async execStreamWithSession(\n command: string,\n sessionId: string,\n options?: StreamOptions\n ): Promise<ReadableStream<Uint8Array>> {\n // Check for cancellation\n if (options?.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n return this.client.commands.executeStream(command, sessionId, {\n timeoutMs: options?.timeout,\n env: options?.env,\n cwd: options?.cwd\n });\n }\n\n /**\n * Stream logs from a background process as a ReadableStream.\n */\n async streamProcessLogs(\n processId: string,\n options?: { signal?: AbortSignal }\n ): Promise<ReadableStream<Uint8Array>> {\n // Check for cancellation\n if (options?.signal?.aborted) {\n throw new Error('Operation was aborted');\n }\n\n return this.client.processes.streamProcessLogs(processId);\n }\n\n async gitCheckout(\n repoUrl: string,\n options: { branch?: string; targetDir?: string; sessionId?: string }\n ) {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.git.checkout(repoUrl, session, {\n branch: options.branch,\n targetDir: options.targetDir\n });\n }\n\n async mkdir(\n path: string,\n options: { recursive?: boolean; sessionId?: string } = {}\n ) {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.mkdir(path, session, {\n recursive: options.recursive\n });\n }\n\n async writeFile(\n path: string,\n content: string,\n options: { encoding?: string; sessionId?: string } = {}\n ) {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.writeFile(path, content, session, {\n encoding: options.encoding\n });\n }\n\n async deleteFile(path: string, sessionId?: string) {\n const session = sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.deleteFile(path, session);\n }\n\n async renameFile(oldPath: string, newPath: string, sessionId?: string) {\n const session = sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.renameFile(oldPath, newPath, session);\n }\n\n async moveFile(\n sourcePath: string,\n destinationPath: string,\n sessionId?: string\n ) {\n const session = sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.moveFile(sourcePath, destinationPath, session);\n }\n\n async readFile(\n path: string,\n options: { encoding?: string; sessionId?: string } = {}\n ) {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.readFile(path, session, {\n encoding: options.encoding\n });\n }\n\n /**\n * Stream a file from the sandbox using Server-Sent Events\n * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities\n * @param path - Path to the file to stream\n * @param options - Optional session ID\n */\n async readFileStream(\n path: string,\n options: { sessionId?: string } = {}\n ): Promise<ReadableStream<Uint8Array>> {\n const session = options.sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.readFileStream(path, session);\n }\n\n async listFiles(\n path: string,\n options?: { recursive?: boolean; includeHidden?: boolean }\n ) {\n const session = await this.ensureDefaultSession();\n return this.client.files.listFiles(path, session, options);\n }\n\n async exists(path: string, sessionId?: string) {\n const session = sessionId ?? (await this.ensureDefaultSession());\n return this.client.files.exists(path, session);\n }\n\n async exposePort(port: number, options: { name?: string; hostname: string }) {\n // Check if hostname is workers.dev domain (doesn't support wildcard subdomains)\n if (options.hostname.endsWith('.workers.dev')) {\n const errorResponse: ErrorResponse = {\n code: ErrorCode.CUSTOM_DOMAIN_REQUIRED,\n message: `Port exposure requires a custom domain. .workers.dev domains do not support wildcard subdomains required for port proxying.`,\n context: { originalError: options.hostname },\n httpStatus: 400,\n timestamp: new Date().toISOString()\n };\n throw new CustomDomainRequiredError(errorResponse);\n }\n\n const sessionId = await this.ensureDefaultSession();\n await this.client.ports.exposePort(port, sessionId, options?.name);\n\n // We need the sandbox name to construct preview URLs\n if (!this.sandboxName) {\n throw new Error(\n 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'\n );\n }\n\n // Generate and store token for this port\n const token = this.generatePortToken();\n this.portTokens.set(port, token);\n await this.persistPortTokens();\n\n const url = this.constructPreviewUrl(\n port,\n this.sandboxName,\n options.hostname,\n token\n );\n\n return {\n url,\n port,\n name: options?.name\n };\n }\n\n async unexposePort(port: number) {\n if (!validatePort(port)) {\n throw new SecurityError(\n `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`\n );\n }\n\n const sessionId = await this.ensureDefaultSession();\n await this.client.ports.unexposePort(port, sessionId);\n\n // Clean up token for this port\n if (this.portTokens.has(port)) {\n this.portTokens.delete(port);\n await this.persistPortTokens();\n }\n }\n\n async getExposedPorts(hostname: string) {\n const sessionId = await this.ensureDefaultSession();\n const response = await this.client.ports.getExposedPorts(sessionId);\n\n // We need the sandbox name to construct preview URLs\n if (!this.sandboxName) {\n throw new Error(\n 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'\n );\n }\n\n return response.ports.map((port) => {\n // Get token for this port - must exist for all exposed ports\n const token = this.portTokens.get(port.port);\n if (!token) {\n throw new Error(\n `Port ${port.port} is exposed but has no token. This should not happen.`\n );\n }\n\n return {\n url: this.constructPreviewUrl(\n port.port,\n this.sandboxName!,\n hostname,\n token\n ),\n port: port.port,\n status: port.status\n };\n });\n }\n\n async isPortExposed(port: number): Promise<boolean> {\n try {\n const sessionId = await this.ensureDefaultSession();\n const response = await this.client.ports.getExposedPorts(sessionId);\n return response.ports.some((exposedPort) => exposedPort.port === port);\n } catch (error) {\n this.logger.error(\n 'Error checking if port is exposed',\n error instanceof Error ? error : new Error(String(error)),\n { port }\n );\n return false;\n }\n }\n\n async validatePortToken(port: number, token: string): Promise<boolean> {\n // First check if port is exposed\n const isExposed = await this.isPortExposed(port);\n if (!isExposed) {\n return false;\n }\n\n // Get stored token for this port - must exist for all exposed ports\n const storedToken = this.portTokens.get(port);\n if (!storedToken) {\n // This should not happen - all exposed ports must have tokens\n this.logger.error(\n 'Port is exposed but has no token - bug detected',\n undefined,\n { port }\n );\n return false;\n }\n\n // Constant-time comparison to prevent timing attacks\n return storedToken === token;\n }\n\n private generatePortToken(): string {\n // Generate cryptographically secure 16-character token using Web Crypto API\n // Available in Cloudflare Workers runtime\n const array = new Uint8Array(12); // 12 bytes = 16 base64url chars (after padding removal)\n crypto.getRandomValues(array);\n\n // Convert to base64url format (URL-safe, no padding, lowercase)\n const base64 = btoa(String.fromCharCode(...array));\n return base64\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '')\n .toLowerCase();\n }\n\n private async persistPortTokens(): Promise<void> {\n // Convert Map to plain object for storage\n const tokensObj: Record<string, string> = {};\n for (const [port, token] of this.portTokens.entries()) {\n tokensObj[port.toString()] = token;\n }\n await this.ctx.storage.put('portTokens', tokensObj);\n }\n\n private constructPreviewUrl(\n port: number,\n sandboxId: string,\n hostname: string,\n token: string\n ): string {\n if (!validatePort(port)) {\n throw new SecurityError(\n `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`\n );\n }\n\n // Hostnames are case-insensitive, routing requests to wrong DO instance when keys contain uppercase letters\n const effectiveId = this.sandboxName || sandboxId;\n const hasUppercase = /[A-Z]/.test(effectiveId);\n if (!this.normalizeId && hasUppercase) {\n throw new SecurityError(\n `Preview URLs require lowercase sandbox IDs. Your ID \"${effectiveId}\" contains uppercase letters.\\n\\n` +\n `To fix this:\\n` +\n `1. Create a new sandbox with: getSandbox(ns, \"${effectiveId}\", { normalizeId: true })\\n` +\n `2. This will create a sandbox with ID: \"${effectiveId.toLowerCase()}\"\\n\\n` +\n `Note: Due to DNS case-insensitivity, IDs with uppercase letters cannot be used with preview URLs.`\n );\n }\n\n const sanitizedSandboxId = sanitizeSandboxId(sandboxId).toLowerCase();\n\n const isLocalhost = isLocalhostPattern(hostname);\n\n if (isLocalhost) {\n const [host, portStr] = hostname.split(':');\n const mainPort = portStr || '80';\n\n try {\n const baseUrl = new URL(`http://${host}:${mainPort}`);\n const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;\n baseUrl.hostname = subdomainHost;\n\n return baseUrl.toString();\n } catch (error) {\n throw new SecurityError(\n `Failed to construct preview URL: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\n }\n }\n\n try {\n const baseUrl = new URL(`https://${hostname}`);\n const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;\n baseUrl.hostname = subdomainHost;\n\n return baseUrl.toString();\n } catch (error) {\n throw new SecurityError(\n `Failed to construct preview URL: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\n }\n }\n\n // ============================================================================\n // Session Management - Advanced Use Cases\n // ============================================================================\n\n /**\n * Create isolated execution session for advanced use cases\n * Returns ExecutionSession with full sandbox API bound to specific session\n */\n async createSession(options?: SessionOptions): Promise<ExecutionSession> {\n const sessionId = options?.id || `session-${Date.now()}`;\n\n const mergedEnv = {\n ...this.envVars,\n ...(options?.env ?? {})\n };\n const envPayload =\n Object.keys(mergedEnv).length > 0 ? mergedEnv : undefined;\n\n // Create session in container\n await this.client.utils.createSession({\n id: sessionId,\n ...(envPayload && { env: envPayload }),\n ...(options?.cwd && { cwd: options.cwd })\n });\n\n // Return wrapper that binds sessionId to all operations\n return this.getSessionWrapper(sessionId);\n }\n\n /**\n * Get an existing session by ID\n * Returns ExecutionSession wrapper bound to the specified session\n *\n * This is useful for retrieving sessions across different requests/contexts\n * without storing the ExecutionSession object (which has RPC lifecycle limitations)\n *\n * @param sessionId - The ID of an existing session\n * @returns ExecutionSession wrapper bound to the session\n */\n async getSession(sessionId: string): Promise<ExecutionSession> {\n // No need to verify session exists in container - operations will fail naturally if it doesn't\n return this.getSessionWrapper(sessionId);\n }\n\n /**\n * Delete an execution session\n * Cleans up session resources and removes it from the container\n * Note: Cannot delete the default session. To reset the default session,\n * use sandbox.destroy() to terminate the entire sandbox.\n *\n * @param sessionId - The ID of the session to delete\n * @returns Result with success status, sessionId, and timestamp\n * @throws Error if attempting to delete the default session\n */\n async deleteSession(sessionId: string): Promise<SessionDeleteResult> {\n // Prevent deletion of default session\n if (this.defaultSession && sessionId === this.defaultSession) {\n throw new Error(\n `Cannot delete default session '${sessionId}'. Use sandbox.destroy() to terminate the sandbox.`\n );\n }\n\n const response = await this.client.utils.deleteSession(sessionId);\n\n // Map HTTP response to result type\n return {\n success: response.success,\n sessionId: response.sessionId,\n timestamp: response.timestamp\n };\n }\n\n /**\n * Internal helper to create ExecutionSession wrapper for a given sessionId\n * Used by both createSession and getSession\n */\n private getSessionWrapper(sessionId: string): ExecutionSession {\n return {\n id: sessionId,\n\n // Command execution - delegate to internal session-aware methods\n exec: (command, options) =>\n this.execWithSession(command, sessionId, options),\n execStream: (command, options) =>\n this.execStreamWithSession(command, sessionId, options),\n\n // Process management\n startProcess: (command, options) =>\n this.startProcess(command, options, sessionId),\n listProcesses: () => this.listProcesses(sessionId),\n getProcess: (id) => this.getProcess(id, sessionId),\n killProcess: (id, signal) => this.killProcess(id, signal),\n killAllProcesses: () => this.killAllProcesses(),\n cleanupCompletedProcesses: () => this.cleanupCompletedProcesses(),\n getProcessLogs: (id) => this.getProcessLogs(id),\n streamProcessLogs: (processId, options) =>\n this.streamProcessLogs(processId, options),\n\n // File operations - pass sessionId via options or parameter\n writeFile: (path, content, options) =>\n this.writeFile(path, content, { ...options, sessionId }),\n readFile: (path, options) =>\n this.readFile(path, { ...options, sessionId }),\n readFileStream: (path) => this.readFileStream(path, { sessionId }),\n mkdir: (path, options) => this.mkdir(path, { ...options, sessionId }),\n deleteFile: (path) => this.deleteFile(path, sessionId),\n renameFile: (oldPath, newPath) =>\n this.renameFile(oldPath, newPath, sessionId),\n moveFile: (sourcePath, destPath) =>\n this.moveFile(sourcePath, destPath, sessionId),\n listFiles: (path, options) =>\n this.client.files.listFiles(path, sessionId, options),\n exists: (path) => this.exists(path, sessionId),\n\n // Git operations\n gitCheckout: (repoUrl, options) =>\n this.gitCheckout(repoUrl, { ...options, sessionId }),\n\n // Environment management - needs special handling\n setEnvVars: async (envVars: Record<string, string>) => {\n try {\n // Set environment variables by executing export commands\n for (const [key, value] of Object.entries(envVars)) {\n const escapedValue = value.replace(/'/g, \"'\\\\''\");\n const exportCommand = `export ${key}='${escapedValue}'`;\n\n const result = await this.client.commands.execute(\n exportCommand,\n sessionId\n );\n\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to set ${key}: ${result.stderr || 'Unknown error'}`\n );\n }\n }\n } catch (error) {\n this.logger.error(\n 'Failed to set environment variables',\n error instanceof Error ? error : new Error(String(error)),\n { sessionId }\n );\n throw error;\n }\n },\n\n // Code interpreter methods - delegate to sandbox's code interpreter\n createCodeContext: (options) =>\n this.codeInterpreter.createCodeContext(options),\n runCode: async (code, options) => {\n const execution = await this.codeInterpreter.runCode(code, options);\n return execution.toJSON();\n },\n runCodeStream: (code, options) =>\n this.codeInterpreter.runCodeStream(code, options),\n listCodeContexts: () => this.codeInterpreter.listCodeContexts(),\n deleteCodeContext: (contextId) =>\n this.codeInterpreter.deleteCodeContext(contextId),\n\n // Bucket mounting - sandbox-level operations\n mountBucket: (bucket, mountPath, options) =>\n this.mountBucket(bucket, mountPath, options),\n unmountBucket: (mountPath) => this.unmountBucket(mountPath)\n };\n }\n\n // ============================================================================\n // Code interpreter methods - delegate to CodeInterpreter wrapper\n // ============================================================================\n\n async createCodeContext(\n options?: CreateContextOptions\n ): Promise<CodeContext> {\n return this.codeInterpreter.createCodeContext(options);\n }\n\n async runCode(\n code: string,\n options?: RunCodeOptions\n ): Promise<ExecutionResult> {\n const execution = await this.codeInterpreter.runCode(code, options);\n return execution.toJSON();\n }\n\n async runCodeStream(\n code: string,\n options?: RunCodeOptions\n ): Promise<ReadableStream> {\n return this.codeInterpreter.runCodeStream(code, options);\n }\n\n async listCodeContexts(): Promise<CodeContext[]> {\n return this.codeInterpreter.listCodeContexts();\n }\n\n async deleteCodeContext(contextId: string): Promise<void> {\n return this.codeInterpreter.deleteCodeContext(contextId);\n }\n}\n","import type { FileChunk, FileMetadata, FileStreamEvent } from '@repo/shared';\n\n/**\n * Parse SSE (Server-Sent Events) lines from a stream\n */\nasync function* parseSSE(\n stream: ReadableStream<Uint8Array>\n): AsyncGenerator<FileStreamEvent> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n\n // Keep the last incomplete line in the buffer\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6); // Remove 'data: ' prefix\n try {\n const event = JSON.parse(data) as FileStreamEvent;\n yield event;\n } catch {\n // Skip invalid JSON events and continue processing\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Stream a file from the sandbox with automatic base64 decoding for binary files\n *\n * @param stream - The ReadableStream from readFileStream()\n * @returns AsyncGenerator that yields FileChunk (string for text, Uint8Array for binary)\n *\n * @example\n * ```ts\n * const stream = await sandbox.readFileStream('/path/to/file.png');\n * for await (const chunk of streamFile(stream)) {\n * if (chunk instanceof Uint8Array) {\n * // Binary chunk\n * console.log('Binary chunk:', chunk.length, 'bytes');\n * } else {\n * // Text chunk\n * console.log('Text chunk:', chunk);\n * }\n * }\n * ```\n */\nexport async function* streamFile(\n stream: ReadableStream<Uint8Array>\n): AsyncGenerator<FileChunk, FileMetadata> {\n let metadata: FileMetadata | null = null;\n\n for await (const event of parseSSE(stream)) {\n switch (event.type) {\n case 'metadata':\n metadata = {\n mimeType: event.mimeType,\n size: event.size,\n isBinary: event.isBinary,\n encoding: event.encoding\n };\n break;\n\n case 'chunk':\n if (!metadata) {\n throw new Error('Received chunk before metadata');\n }\n\n if (metadata.isBinary && metadata.encoding === 'base64') {\n // Decode base64 to Uint8Array for binary files\n const binaryString = atob(event.data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n yield bytes;\n } else {\n // Text files - yield as-is\n yield event.data;\n }\n break;\n\n case 'complete':\n if (!metadata) {\n throw new Error('Stream completed without metadata');\n }\n return metadata;\n\n case 'error':\n throw new Error(`File streaming error: ${event.error}`);\n }\n }\n\n throw new Error('Stream ended unexpectedly');\n}\n\n/**\n * Collect an entire file into memory from a stream\n *\n * @param stream - The ReadableStream from readFileStream()\n * @returns Object containing the file content and metadata\n *\n * @example\n * ```ts\n * const stream = await sandbox.readFileStream('/path/to/file.txt');\n * const { content, metadata } = await collectFile(stream);\n * console.log('Content:', content);\n * console.log('MIME type:', metadata.mimeType);\n * ```\n */\nexport async function collectFile(stream: ReadableStream<Uint8Array>): Promise<{\n content: string | Uint8Array;\n metadata: FileMetadata;\n}> {\n const chunks: Array<string | Uint8Array> = [];\n\n // Iterate through the generator and get the return value (metadata)\n const generator = streamFile(stream);\n let result = await generator.next();\n\n while (!result.done) {\n chunks.push(result.value);\n result = await generator.next();\n }\n\n const metadata = result.value;\n\n if (!metadata) {\n throw new Error('Failed to get file metadata');\n }\n\n // Combine chunks based on type\n if (metadata.isBinary) {\n // Binary file - combine Uint8Arrays\n const totalLength = chunks.reduce(\n (sum, chunk) => sum + (chunk instanceof Uint8Array ? chunk.length : 0),\n 0\n );\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n if (chunk instanceof Uint8Array) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n }\n return { content: combined, metadata };\n } else {\n // Text file - combine strings\n const combined = chunks.filter((c) => typeof c === 'string').join('');\n return { content: combined, metadata };\n }\n}\n"],"mappings":";;;;;;;;AAIA,MAAa,YAAY;CAErB,gBAAgB;CAEhB,mBAAmB;CAEnB,aAAa;CAEb,cAAc;CACd,eAAe;CAEf,UAAU;CACV,gBAAgB;CAChB,eAAe;CACf,WAAW;CACX,eAAe;CACf,gBAAgB;CAChB,kBAAkB;CAElB,mBAAmB;CAEnB,2BAA2B;CAC3B,iBAAiB;CAEjB,yBAAyB;CACzB,oBAAoB;CAEpB,mBAAmB;CAEnB,2BAA2B;CAC3B,eAAe;CAEf,sBAAsB;CACtB,aAAa;CAEb,kBAAkB;CAElB,qBAAqB;CACrB,cAAc;CAEd,wBAAwB;CACxB,sBAAsB;CAEtB,wBAAwB;CAExB,0BAA0B;CAC1B,sBAAsB;CAEtB,iBAAiB;CAEjB,mBAAmB;CAEnB,iBAAiB;CAEjB,kBAAkB;CAClB,qBAAqB;CACrB,sBAAsB;CAEtB,oBAAoB;CACpB,kBAAkB;CAClB,qBAAqB;CACrB,sBAAsB;CAEtB,uBAAuB;CAEvB,mBAAmB;CAEnB,sBAAsB;CAEtB,mBAAmB;CAEnB,uBAAuB;CACvB,eAAe;CACf,gBAAgB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