{"version":3,"sources":["../src/api/index.ts","../src/api/metadata.ts","../package.json","../src/utils.ts","../src/undici.ts","../src/api/http2.ts","../src/errors.ts","../src/logs.ts","../src/connectionConfig.ts","../src/sandbox/signature.ts","../src/sandbox/filesystem/index.ts","../src/envd/api.ts","../src/envd/rpc.ts","../src/envd/versions.ts","../src/envd/filesystem/filesystem_pb.ts","../src/sandbox/filesystem/watchHandle.ts","../src/sandbox/commands/commandHandle.ts","../src/sandbox/network.ts","../src/sandbox/git/utils.ts","../src/sandbox/git/index.ts","../src/volume/client.ts","../src/volume/types.ts","../src/volume/index.ts","../src/sandbox/index.ts","../src/envd/http2.ts","../src/sandbox/commands/index.ts","../src/envd/process/process_pb.ts","../src/sandbox/commands/pty.ts","../src/sandbox/sandboxApi.ts","../src/template/logger.ts","../src/template/utils.ts","../src/template/consts.ts","../src/template/buildApi.ts","../src/template/dockerfileParser.ts","../src/template/readycmd.ts","../src/template/index.ts","../src/index.ts"],"sourcesContent":["import createClient, { FetchResponse } from 'openapi-fetch'\n\nimport type { components, paths } from './schema.gen'\nimport { defaultHeaders } from './metadata'\nimport { createApiFetch } from './http2'\nimport { ConnectionConfig } from '../connectionConfig'\nimport { AuthenticationError, RateLimitError, SandboxError } from '../errors'\nimport { createApiLogger } from '../logs'\n\nexport function handleApiError(\n  response: FetchResponse<any, any, any>,\n  errorClass: new (\n    message: string,\n    stackTrace?: string\n  ) => Error = SandboxError,\n  stackTrace?: string\n): Error | undefined {\n  // openapi-fetch returns empty string for error when response body is empty,\n  // so we check !== undefined instead of truthiness\n  if (response.error === undefined) {\n    return\n  }\n\n  if (response.response.status === 401) {\n    const message = 'Unauthorized, please check your credentials.'\n    const content = response.error?.message ?? response.error\n\n    if (content) {\n      return new AuthenticationError(`${message} - ${content}`)\n    }\n    return new AuthenticationError(message)\n  }\n\n  if (response.response.status === 429) {\n    const message = 'Rate limit exceeded, please try again later'\n    const content = response.error?.message ?? response.error\n\n    if (content) {\n      return new RateLimitError(`${message} - ${content}`)\n    }\n    return new RateLimitError(message)\n  }\n\n  const message = response.error?.message ?? response.error\n  return new errorClass(`${response.response.status}: ${message}`, stackTrace)\n}\n\n/**\n * Client for interacting with the E2B API.\n */\nclass ApiClient {\n  readonly api: ReturnType<typeof createClient<paths>>\n\n  constructor(\n    config: ConnectionConfig,\n    opts: {\n      requireAccessToken?: boolean\n      requireApiKey?: boolean\n    } = { requireAccessToken: false, requireApiKey: false }\n  ) {\n    if (opts?.requireApiKey && !config.apiKey) {\n      throw new AuthenticationError(\n        'API key is required, please visit the Team tab at https://e2b.dev/dashboard to get your API key. ' +\n          'You can either set the environment variable `E2B_API_KEY` ' +\n          \"or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })\"\n      )\n    }\n\n    if (opts?.requireAccessToken && !config.accessToken) {\n      throw new AuthenticationError(\n        'Access token is required, please visit the Personal tab at https://e2b.dev/dashboard to get your access token. ' +\n          'You can set the environment variable `E2B_ACCESS_TOKEN` or pass the `accessToken` in options.'\n      )\n    }\n\n    this.api = createClient<paths>({\n      baseUrl: config.apiUrl,\n      fetch: createApiFetch(),\n      // In HTTP 1.1, all connections are considered persistent unless declared otherwise\n      // keepalive: true,\n      headers: {\n        ...defaultHeaders,\n        ...(config.apiKey && { 'X-API-KEY': config.apiKey }),\n        ...(config.accessToken && {\n          Authorization: `Bearer ${config.accessToken}`,\n        }),\n        ...config.headers,\n      },\n      querySerializer: {\n        array: {\n          style: 'form',\n          explode: false,\n        },\n      },\n    })\n\n    if (config.logger) {\n      this.api.use(createApiLogger(config.logger))\n    }\n  }\n}\n\nexport type { components, paths }\nexport { ApiClient }\n","import platform from 'platform'\n\nimport { version } from '../../package.json'\nimport { runtime, runtimeVersion } from '../utils'\n\nexport { version }\n\nexport const defaultHeaders = {\n  browser: (typeof window !== 'undefined' && platform.name) || 'unknown',\n  lang: 'js',\n  lang_version: runtimeVersion,\n  package_version: version,\n  publisher: 'e2b',\n  sdk_runtime: runtime,\n  system: platform.os?.family || 'unknown',\n}\n\nexport function getEnvVar(name: string) {\n  if (runtime === 'deno') {\n    // @ts-ignore\n    return Deno.env.get(name)\n  }\n\n  if (typeof process === 'undefined') {\n    return ''\n  }\n\n  return process.env[name]\n}\n","{\n  \"name\": \"e2b\",\n  \"version\": \"2.24.0\",\n  \"description\": \"E2B SDK that give agents cloud environments\",\n  \"homepage\": \"https://e2b.dev\",\n  \"license\": \"MIT\",\n  \"author\": {\n    \"name\": \"FoundryLabs, Inc.\",\n    \"email\": \"hello@e2b.dev\",\n    \"url\": \"https://e2b.dev\"\n  },\n  \"bugs\": \"https://github.com/e2b-dev/e2b/issues\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/e2b-dev/e2b\",\n    \"directory\": \"packages/js-sdk\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"sideEffects\": false,\n  \"main\": \"dist/index.js\",\n  \"module\": \"dist/index.mjs\",\n  \"types\": \"dist/index.d.ts\",\n  \"scripts\": {\n    \"prepublishOnly\": \"pnpm build\",\n    \"build\": \"tsc --noEmit && tsup\",\n    \"dev\": \"tsup --watch\",\n    \"example\": \"tsx example.mts\",\n    \"test\": \"vitest run\",\n    \"generate\": \"npm-run-all generate:* && pnpm run format\",\n    \"generate:api\": \"python ./../../spec/remove_extra_tags.py sandboxes snapshots templates tags auth volumes && openapi-typescript ../../spec/openapi_generated.yml -x api_key --array-length --alphabetize --default-non-nullable false --output src/api/schema.gen.ts\",\n    \"generate:envd\": \"cd ../../spec/envd && buf generate --template buf-js.gen.yaml\\n\",\n    \"generate:envd-api\": \"openapi-typescript ../../spec/envd/envd.yaml -x api_key --array-length --alphabetize --output src/envd/schema.gen.ts\",\n    \"generate:volume-api\": \"openapi-typescript ../../spec/openapi-volumecontent.yml -x api_key --array-length --alphabetize --output src/volume/schema.gen.ts\",\n    \"generate:mcp\": \"json2ts -i ./../../spec/mcp-server.json -o src/sandbox/mcp.d.ts --unreachableDefinitions --style.singleQuote --no-style.semi\",\n    \"check-deps\": \"knip\",\n    \"pretest\": \"npx playwright install --with-deps chromium\",\n    \"postPublish\": \"./scripts/post-publish.sh || true\",\n    \"test:bun\": \"bun test tests/runtimes/bun --env-file=.env\",\n    \"test:deno\": \"deno test tests/runtimes/deno/ --allow-net --allow-read --allow-env --unstable-sloppy-imports --trace-leaks\",\n    \"test:integration\": \"E2B_INTEGRATION_TEST=1 vitest run tests/integration/**\",\n    \"typecheck\": \"tsc --noEmit\",\n    \"lint\": \"eslint src/ tests/\",\n    \"format\": \"prettier --write src/ tests/ example.mts\"\n  },\n  \"devDependencies\": {\n    \"@testing-library/react\": \"^16.2.0\",\n    \"@types/node\": \"^20.19.19\",\n    \"@types/platform\": \"^1.3.6\",\n    \"@types/react\": \"^18.3.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^7.11.0\",\n    \"@typescript-eslint/parser\": \"^7.11.0\",\n    \"@vitejs/plugin-react\": \"^4.3.4\",\n    \"@vitest/browser\": \"^3.2.4\",\n    \"dotenv\": \"^16.4.5\",\n    \"eslint\": \"^8.57.1\",\n    \"json-schema-to-typescript\": \"^15.0.4\",\n    \"knip\": \"^5.43.6\",\n    \"msw\": \"^2.12.10\",\n    \"npm-run-all\": \"^4.1.5\",\n    \"openapi-typescript\": \"^7.9.1\",\n    \"playwright\": \"^1.55.1\",\n    \"react\": \"^18.3.1\",\n    \"tsup\": \"^8.4.0\",\n    \"typescript\": \"^5.4.5\",\n    \"vitest\": \"^3.2.4\",\n    \"vitest-browser-react\": \"^0.1.1\"\n  },\n  \"files\": [\n    \"dist\",\n    \"README.md\",\n    \"package.json\"\n  ],\n  \"keywords\": [\n    \"e2b\",\n    \"ai-agents\",\n    \"agents\",\n    \"ai\",\n    \"code-interpreter\",\n    \"sandbox\",\n    \"code\",\n    \"runtime\",\n    \"vm\",\n    \"nodejs\",\n    \"javascript\",\n    \"typescript\"\n  ],\n  \"dependencies\": {\n    \"@bufbuild/protobuf\": \"^2.6.2\",\n    \"@connectrpc/connect\": \"2.0.0-rc.3\",\n    \"@connectrpc/connect-web\": \"2.0.0-rc.3\",\n    \"chalk\": \"^5.3.0\",\n    \"compare-versions\": \"^6.1.0\",\n    \"dockerfile-ast\": \"^0.7.1\",\n    \"glob\": \"^11.1.0\",\n    \"openapi-fetch\": \"^0.14.1\",\n    \"platform\": \"^1.3.6\",\n    \"tar\": \"^7.5.11\",\n    \"undici\": \"^7.25.0\"\n  },\n  \"engines\": {\n    \"node\": \">=20.18.1\"\n  },\n  \"browserslist\": [\n    \"defaults\"\n  ]\n}\n","import platform from 'platform'\n\ndeclare let window: any\n\ntype Runtime =\n  | 'node'\n  | 'browser'\n  | 'deno'\n  | 'bun'\n  | 'vercel-edge'\n  | 'cloudflare-worker'\n  | 'unknown'\n\nfunction getRuntime(): { runtime: Runtime; version: string } {\n  // @ts-ignore\n  if ((globalThis as any).Bun) {\n    // @ts-ignore\n    return { runtime: 'bun', version: globalThis.Bun.version }\n  }\n\n  // @ts-ignore\n  if ((globalThis as any).Deno) {\n    // @ts-ignore\n    return { runtime: 'deno', version: globalThis.Deno.version.deno }\n  }\n\n  if ((globalThis as any).process?.release?.name === 'node') {\n    return { runtime: 'node', version: platform.version || 'unknown' }\n  }\n\n  // @ts-ignore\n  if (typeof EdgeRuntime === 'string') {\n    return { runtime: 'vercel-edge', version: 'unknown' }\n  }\n\n  if ((globalThis as any).navigator?.userAgent === 'Cloudflare-Workers') {\n    return { runtime: 'cloudflare-worker', version: 'unknown' }\n  }\n\n  if (typeof window !== 'undefined') {\n    return { runtime: 'browser', version: platform.version || 'unknown' }\n  }\n\n  return { runtime: 'unknown', version: 'unknown' }\n}\n\nexport const { runtime, version: runtimeVersion } = getRuntime()\n\nexport async function sha256(data: string): Promise<string> {\n  // Use WebCrypto API if available\n  if (typeof crypto !== 'undefined') {\n    const encoder = new TextEncoder()\n    const dataBuffer = encoder.encode(data)\n    const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer)\n    const hashArray = new Uint8Array(hashBuffer)\n    return btoa(String.fromCharCode(...hashArray))\n  }\n\n  // Use Node.js crypto if WebCrypto is not available\n  // eslint-disable-next-line @typescript-eslint/no-var-requires\n  const { createHash } = require('node:crypto')\n  const hash = createHash('sha256').update(data, 'utf8').digest()\n  return hash.toString('base64')\n}\n\nexport function timeoutToSeconds(timeout: number): number {\n  return Math.ceil(timeout / 1000)\n}\n\nexport function dynamicRequire<T>(module: string): T {\n  if (runtime === 'browser') {\n    throw new Error('Browser runtime is not supported for require')\n  }\n\n  return require(module)\n}\n\nexport async function dynamicImport<T>(module: string): Promise<T> {\n  if (runtime === 'browser') {\n    throw new Error('Browser runtime is not supported for dynamic import')\n  }\n\n  // @ts-ignore\n  return await import(module)\n}\n\n// Source: https://github.com/chalk/ansi-regex/blob/main/index.js\nfunction ansiRegex({ onlyFirst = false } = {}) {\n  // Valid string terminator sequences are BEL, ESC\\, and 0x9c\n  const ST = '(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)'\n  // OSC sequences only: ESC ] ... ST (non-greedy until the first ST)\n  const osc = `(?:\\\\u001B\\\\][\\\\s\\\\S]*?${ST})`\n  // CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte\n  const csi =\n    '[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]'\n\n  const pattern = `${osc}|${csi}`\n\n  return new RegExp(pattern, onlyFirst ? undefined : 'g')\n}\n\nexport function stripAnsi(text: string): string {\n  return text.replace(ansiRegex(), '')\n}\n\nexport async function wait(ms: number) {\n  return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Convert data to a Blob, avoiding unnecessary conversions when possible.\n */\nexport function toBlob(\n  data: string | ArrayBuffer | Blob | ReadableStream\n): Blob | Promise<Blob> {\n  // Already a Blob - use directly\n  if (data instanceof Blob) {\n    return data\n  }\n  // String or ArrayBuffer - create Blob\n  if (typeof data === 'string' || data instanceof ArrayBuffer) {\n    return new Blob([data])\n  }\n  // ReadableStream - must consume to get Blob\n  return new Response(data).blob()\n}\n\n/**\n * Escape a string for safe inclusion in a single-quoted shell argument.\n * Equivalent to Python's shlex.quote().\n */\nexport function shellQuote(s: string): string {\n  return \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\"\n}\n\n/**\n * Prepare data for upload as a BodyInit, optionally gzip-compressed.\n * When gzip is enabled, compresses the data and returns a Blob.\n */\nexport async function toUploadBody(\n  data: string | ArrayBuffer | Blob | ReadableStream,\n  gzip?: boolean\n): Promise<BodyInit> {\n  if (gzip) {\n    const stream =\n      data instanceof ReadableStream\n        ? data\n        : data instanceof Blob\n          ? data.stream()\n          : new Blob([data]).stream()\n    const compressed = stream.pipeThrough(new CompressionStream('gzip'))\n    return new Response(compressed).blob()\n  }\n\n  return toBlob(data)\n}\n","export type UndiciRequestInit = RequestInit & {\n  dispatcher?: unknown\n  duplex?: 'half'\n}\n\nexport type UndiciModule = {\n  Agent: new (options: { allowH2: true; connections?: number }) => unknown\n  fetch: unknown\n}\n\nexport async function loadUndici(): Promise<UndiciModule | undefined> {\n  try {\n    // Keep this import opaque to bundlers. It must resolve as a package name\n    // from the runtime environment, not as a path relative to this file.\n    // eslint-disable-next-line no-new-func\n    const importModule = new Function(\n      'moduleName',\n      'return import(moduleName)'\n    ) as (moduleName: string) => Promise<UndiciModule>\n\n    return await importModule('undici')\n  } catch {\n    return undefined\n  }\n}\n\nexport function toUndiciRequestInput(\n  input: RequestInfo | URL,\n  init?: RequestInit\n): { input: RequestInfo | URL; init?: RequestInit & { duplex?: 'half' } } {\n  if (!(input instanceof Request)) {\n    return { input, init }\n  }\n\n  const requestInit: RequestInit & { duplex?: 'half' } = {\n    body: input.body,\n    cache: input.cache,\n    credentials: input.credentials,\n    headers: input.headers,\n    integrity: input.integrity,\n    keepalive: input.keepalive,\n    method: input.method,\n    mode: input.mode,\n    redirect: input.redirect,\n    referrer: input.referrer,\n    referrerPolicy: input.referrerPolicy,\n    signal: input.signal,\n    ...init,\n  }\n\n  if (requestInit.body) {\n    requestInit.duplex = 'half'\n  }\n\n  return {\n    input: input.url,\n    init: requestInit,\n  }\n}\n","import { runtime } from '../utils'\nimport {\n  loadUndici,\n  toUndiciRequestInput,\n  type UndiciModule,\n  type UndiciRequestInit,\n} from '../undici'\n\nconst API_CONNECTION_LIMIT = 100\nconst API_UNDICI_FALLBACK_WARNING =\n  'Failed to load undici for API HTTP/2 transport; falling back to global fetch.'\n\nlet apiFetch: typeof fetch | undefined\nlet hasWarnedUndiciFallback = false\n\nexport function createApiFetch(): typeof fetch {\n  if (apiFetch) {\n    return apiFetch\n  }\n\n  apiFetch = createApiFetchForRuntime(runtime)\n\n  return apiFetch\n}\n\nexport function createApiFetchForRuntime(\n  currentRuntime = runtime,\n  options: {\n    connectionLimit?: number\n    loadUndici?: () => Promise<UndiciModule | undefined>\n  } = { connectionLimit: API_CONNECTION_LIMIT }\n): typeof fetch {\n  if (currentRuntime !== 'node') {\n    return fetch\n  }\n\n  let fetcherPromise: Promise<typeof fetch> | undefined\n\n  return (async (input, init) => {\n    fetcherPromise ??= buildApiFetcher(options)\n    const fetcher = await fetcherPromise\n\n    return fetcher(input, init)\n  }) as typeof fetch\n}\n\nasync function buildApiFetcher(options: {\n  connectionLimit?: number\n  loadUndici?: () => Promise<UndiciModule | undefined>\n}): Promise<typeof fetch> {\n  const undici = await (options.loadUndici ?? loadUndici)()\n\n  if (!undici) {\n    warnUndiciFallback()\n\n    return fetch\n  }\n\n  const { Agent, fetch: undiciFetch } = undici\n  const dispatcher = new Agent({\n    allowH2: true,\n    connections: options.connectionLimit,\n  })\n  const fetchWithDispatcher = undiciFetch as unknown as (\n    input: RequestInfo | URL,\n    init?: UndiciRequestInit\n  ) => Promise<Response>\n\n  return ((input, init) => {\n    const request = toUndiciRequestInput(input, init)\n\n    return fetchWithDispatcher(request.input, {\n      ...request.init,\n      dispatcher,\n    })\n  }) as typeof fetch\n}\n\nfunction warnUndiciFallback() {\n  if (hasWarnedUndiciFallback) {\n    return\n  }\n\n  hasWarnedUndiciFallback = true\n  console.warn(API_UNDICI_FALLBACK_WARNING)\n}\n","// This is the message for the sandbox timeout error when the response code is 502/Unavailable\nexport function formatSandboxTimeoutError(message: string) {\n  return new TimeoutError(\n    `${message}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n  )\n}\n\n/**\n * Base class for all sandbox errors.\n *\n * Thrown when general sandbox errors occur.\n */\nexport class SandboxError extends Error {\n  constructor(message?: string, stackTrace?: string) {\n    super(message)\n    this.name = 'SandboxError'\n    if (stackTrace) {\n      this.stack = stackTrace\n    }\n  }\n}\n\n/**\n * Thrown when a timeout error occurs.\n *\n * The [unavailable] error type is caused by sandbox timeout.\n *\n * The [canceled] error type is caused by exceeding request timeout.\n *\n * The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc.\n *\n * The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly.\n */\nexport class TimeoutError extends SandboxError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'TimeoutError'\n  }\n}\n\n/**\n * Thrown when an invalid argument is provided.\n */\nexport class InvalidArgumentError extends SandboxError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'InvalidArgumentError'\n  }\n}\n\n/**\n * Thrown when there is not enough disk space.\n */\nexport class NotEnoughSpaceError extends SandboxError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'NotEnoughSpaceError'\n  }\n}\n\n/**\n * Thrown when a resource is not found.\n *\n * @deprecated Use {@link FileNotFoundError} or {@link SandboxNotFoundError} instead. This class will be removed in the next major version.\n */\nexport class NotFoundError extends SandboxError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'NotFoundError'\n  }\n}\n\n/**\n * Thrown when a file or directory is not found inside a sandbox.\n */\nexport class FileNotFoundError extends NotFoundError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'FileNotFoundError'\n  }\n}\n\n/**\n * Thrown when a sandbox is not found (e.g. it doesn't exist or is no longer running).\n */\nexport class SandboxNotFoundError extends NotFoundError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'SandboxNotFoundError'\n  }\n}\n\n/**\n * Thrown when authentication fails.\n */\nexport class AuthenticationError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = 'AuthenticationError'\n  }\n}\n\n/**\n * Thrown when git authentication fails.\n */\nexport class GitAuthError extends AuthenticationError {\n  constructor(message: string) {\n    super(message)\n    this.name = 'GitAuthError'\n  }\n}\n\n/**\n * Thrown when git upstream tracking is missing.\n */\nexport class GitUpstreamError extends SandboxError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'GitUpstreamError'\n  }\n}\n\n/**\n * Thrown when the template uses old envd version. It isn't compatible with the new SDK.\n */\nexport class TemplateError extends SandboxError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'TemplateError'\n  }\n}\n\n/**\n * Thrown when the API rate limit is exceeded.\n */\nexport class RateLimitError extends SandboxError {\n  constructor(message: string) {\n    super(message)\n    this.name = 'RateLimitError'\n  }\n}\n\n/**\n * Thrown when the build fails.\n */\nexport class BuildError extends Error {\n  constructor(message: string, stackTrace?: string) {\n    super(message)\n    this.name = 'BuildError'\n    if (stackTrace) {\n      this.stack = stackTrace\n    }\n  }\n}\n\n/**\n * Thrown when the file upload fails.\n */\nexport class FileUploadError extends BuildError {\n  constructor(message: string, stackTrace?: string) {\n    super(message, stackTrace)\n    this.name = 'FileUploadError'\n  }\n}\n\n/**\n * Base class for all volume errors.\n *\n * Thrown when general volume errors occur.\n */\nexport class VolumeError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = 'VolumeError'\n  }\n}\n","import type { Interceptor } from '@connectrpc/connect'\nimport type { Middleware } from 'openapi-fetch'\n\n/**\n * Logger interface compatible with {@link console} used for logging Sandbox messages.\n */\nexport interface Logger {\n  /**\n   * Debug level logging method.\n   */\n  debug?: (...args: any[]) => void\n  /**\n   * Info level logging method.\n   */\n  info?: (...args: any[]) => void\n  /**\n   * Warn level logging method.\n   */\n  warn?: (...args: any[]) => void\n  /**\n   * Error level logging method.\n   */\n  error?: (...args: any[]) => void\n}\n\nfunction formatLog(log: any) {\n  return JSON.parse(JSON.stringify(log))\n}\n\nexport function createRpcLogger(logger: Logger): Interceptor {\n  async function* logEach(stream: AsyncIterable<any>) {\n    for await (const m of stream) {\n      logger.debug?.('Response stream:', formatLog(m))\n      yield m\n    }\n  }\n\n  return (next) => async (req) => {\n    logger.info?.(`Request: POST ${req.url}`)\n\n    const res = await next(req)\n    if (res.stream) {\n      return {\n        ...res,\n        message: logEach(res.message),\n      }\n    } else {\n      logger.info?.('Response:', formatLog(res.message))\n    }\n\n    return res\n  }\n}\n\nexport function createApiLogger(logger: Logger): Middleware {\n  return {\n    async onRequest({ request }) {\n      logger.info?.(`Request ${request.method} ${request.url}`)\n      return request\n    },\n    async onResponse({ response }) {\n      if (response.status >= 400) {\n        logger.error?.('Response:', response.status, response.statusText)\n      } else {\n        logger.info?.('Response:', response.status, response.statusText)\n      }\n\n      return response\n    },\n  }\n}\n","import { Logger } from './logs'\nimport { getEnvVar, version } from './api/metadata'\n\nexport const REQUEST_TIMEOUT_MS = 60_000 // 60 seconds\nexport const DEFAULT_SANDBOX_TIMEOUT_MS = 300_000 // 300 seconds\nexport const KEEPALIVE_PING_INTERVAL_SEC = 50 // 50 seconds\n\nexport const KEEPALIVE_PING_HEADER = 'Keepalive-Ping-Interval'\n\n/**\n * Connection options for requests to the API.\n */\nexport interface ConnectionOpts {\n  /**\n   * E2B API key to use for authentication.\n   *\n   * @default E2B_API_KEY // environment variable\n   */\n  apiKey?: string\n  /**\n   * E2B access token to use for authentication.\n   *\n   * @default E2B_ACCESS_TOKEN // environment variable\n   */\n  accessToken?: string\n  /**\n   * Domain to use for the API.\n   *\n   * @default E2B_DOMAIN // environment variable or `e2b.app`\n   */\n  domain?: string\n  /**\n   * API Url to use for the API.\n   * @internal\n   * @default E2B_API_URL // environment variable or `https://api.${domain}`\n   */\n  apiUrl?: string\n  /**\n   * Sandbox Url to use for the API.\n   * @internal\n   * @default E2B_SANDBOX_URL // environment variable or `https://${port}-${sandboxID}.${domain}`\n   */\n  sandboxUrl?: string\n  /**\n   * If true the SDK starts in the debug mode and connects to the local envd API server.\n   * @internal\n   * @default E2B_DEBUG // environment variable or `false`\n   */\n  debug?: boolean\n  /**\n   * Timeout for requests to the API in **milliseconds**.\n   *\n   * @default 60_000 // 60 seconds\n   */\n  requestTimeoutMs?: number\n  /**\n   * Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, {@link console}.\n   */\n  logger?: Logger\n\n  /**\n   * Additional headers to send with the request.\n   */\n  headers?: Record<string, string>\n\n  /**\n   * An optional `AbortSignal` that can be used to cancel the in-flight request.\n   * When the signal is aborted, the underlying `fetch` is aborted and the\n   * returned promise rejects with an `AbortError`.\n   */\n  signal?: AbortSignal\n}\n\n/**\n * Build an `AbortSignal` that combines an optional request-timeout signal\n * (via `AbortSignal.timeout`) with an optional user-provided signal.\n *\n * Returns `undefined` when neither input would produce a signal.\n *\n * @internal\n */\nexport function buildRequestSignal(\n  requestTimeoutMs: number | undefined,\n  userSignal: AbortSignal | undefined\n): AbortSignal | undefined {\n  const timeoutSignal = requestTimeoutMs\n    ? AbortSignal.timeout(requestTimeoutMs)\n    : undefined\n\n  if (timeoutSignal && userSignal) {\n    return AbortSignal.any([timeoutSignal, userSignal])\n  }\n\n  return timeoutSignal ?? userSignal\n}\n\n/**\n * Set up an internal `AbortController` for a streaming request.\n *\n * Until `clearStartTimeout` is called, the controller aborts when either\n *  - the optional user signal aborts, or\n *  - the optional request timeout elapses (used to bound the initial\n *    handshake; long-lived streams should call `clearStartTimeout` once\n *    the handshake succeeds).\n *\n * The user-signal listener stays attached for the full stream lifetime\n * so the caller can cancel a long-running stream by aborting the signal.\n *\n * `cleanup` is idempotent and detaches the listener, clears the handshake\n * timer (if still pending), and aborts the controller. Call it when the\n * stream finishes or when startup fails.\n *\n * @internal\n */\nexport function setupRequestController(\n  requestTimeoutMs: number | undefined,\n  userSignal: AbortSignal | undefined\n): {\n  controller: AbortController\n  clearStartTimeout: () => void\n  cleanup: () => void\n} {\n  const controller = new AbortController()\n\n  const onUserAbort = () => controller.abort(userSignal?.reason)\n  if (userSignal) {\n    if (userSignal.aborted) {\n      controller.abort(userSignal.reason)\n    } else {\n      userSignal.addEventListener('abort', onUserAbort, { once: true })\n    }\n  }\n\n  let reqTimeout: ReturnType<typeof setTimeout> | undefined = requestTimeoutMs\n    ? setTimeout(\n        () =>\n          controller.abort(\n            new DOMException(\n              `Request handshake timed out after ${requestTimeoutMs}ms`,\n              'TimeoutError'\n            )\n          ),\n        requestTimeoutMs\n      )\n    : undefined\n\n  const clearStartTimeout = () => {\n    if (reqTimeout) {\n      clearTimeout(reqTimeout)\n      reqTimeout = undefined\n    }\n  }\n\n  let cleaned = false\n  const cleanup = () => {\n    if (cleaned) return\n    cleaned = true\n    userSignal?.removeEventListener('abort', onUserAbort)\n    clearStartTimeout()\n    controller.abort()\n  }\n\n  return { controller, clearStartTimeout, cleanup }\n}\n\n/**\n * Configuration for connecting to the API.\n */\nexport class ConnectionConfig {\n  public static envdPort = 49983\n\n  readonly debug: boolean\n  readonly domain: string\n  readonly apiUrl: string\n  readonly sandboxUrl?: string\n  readonly logger?: Logger\n\n  readonly requestTimeoutMs: number\n\n  readonly apiKey?: string\n  readonly accessToken?: string\n\n  readonly headers?: Record<string, string>\n\n  constructor(opts?: ConnectionOpts) {\n    this.apiKey = opts?.apiKey || ConnectionConfig.apiKey\n    this.debug = opts?.debug || ConnectionConfig.debug\n    this.domain = opts?.domain || ConnectionConfig.domain\n    this.accessToken = opts?.accessToken || ConnectionConfig.accessToken\n    this.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MS\n    this.logger = opts?.logger\n    this.headers = opts?.headers || {}\n    this.headers['User-Agent'] = `e2b-js-sdk/${version}`\n\n    this.apiUrl =\n      opts?.apiUrl ||\n      ConnectionConfig.apiUrl ||\n      (this.debug ? 'http://localhost:3000' : `https://api.${this.domain}`)\n\n    this.sandboxUrl = opts?.sandboxUrl || ConnectionConfig.sandboxUrl\n  }\n\n  private static get domain() {\n    return getEnvVar('E2B_DOMAIN') || 'e2b.app'\n  }\n\n  private static get apiUrl() {\n    return getEnvVar('E2B_API_URL')\n  }\n\n  private static get sandboxUrl() {\n    return getEnvVar('E2B_SANDBOX_URL')\n  }\n\n  private static get debug() {\n    return (getEnvVar('E2B_DEBUG') || 'false').toLowerCase() === 'true'\n  }\n\n  private static get apiKey() {\n    return getEnvVar('E2B_API_KEY')\n  }\n\n  private static get accessToken() {\n    return getEnvVar('E2B_ACCESS_TOKEN')\n  }\n\n  getSignal(requestTimeoutMs?: number, signal?: AbortSignal) {\n    return buildRequestSignal(requestTimeoutMs ?? this.requestTimeoutMs, signal)\n  }\n\n  getSandboxUrl(\n    sandboxId: string,\n    opts: { sandboxDomain: string; envdPort: number }\n  ) {\n    if (this.sandboxUrl) {\n      return this.sandboxUrl\n    }\n\n    return `${this.debug ? 'http' : 'https'}://${this.getHost(sandboxId, opts.envdPort, opts.sandboxDomain)}`\n  }\n\n  getHost(sandboxId: string, port: number, sandboxDomain: string) {\n    if (this.debug) {\n      return `localhost:${port}`\n    }\n\n    return `${port}-${sandboxId}.${sandboxDomain ?? this.domain}`\n  }\n}\n\n/**\n * User used for the operation in the sandbox.\n */\n\nexport const defaultUsername: Username = 'user'\nexport type Username = string\n","import { sha256 } from '../utils'\n\n/**\n * Get the URL signature for the specified path, operation and user.\n *\n * @param path Path to the file in the sandbox.\n *\n * @param operation File system operation. Can be either `read` or `write`.\n *\n * @param user Sandbox user.\n *\n * @param expirationInSeconds Optional signature expiration time in seconds.\n */\n\ninterface SignatureOpts {\n  path: string\n  operation: 'read' | 'write'\n  user: string | undefined\n  expirationInSeconds?: number\n  envdAccessToken?: string\n}\n\nexport async function getSignature({\n  path,\n  operation,\n  user,\n  expirationInSeconds,\n  envdAccessToken,\n}: SignatureOpts): Promise<{ signature: string; expiration: number | null }> {\n  if (!envdAccessToken) {\n    throw new Error(\n      'Access token is not set and signature cannot be generated!'\n    )\n  }\n\n  // expiration is unix timestamp\n  const signatureExpiration = expirationInSeconds\n    ? Math.floor(Date.now() / 1000) + expirationInSeconds\n    : null\n  let signatureRaw: string\n\n  // if user is undefined, set it to empty string to handle default user\n  if (user == undefined) {\n    user = ''\n  }\n\n  if (signatureExpiration === null) {\n    signatureRaw = `${path}:${operation}:${user}:${envdAccessToken}`\n  } else {\n    signatureRaw = `${path}:${operation}:${user}:${envdAccessToken}:${signatureExpiration.toString()}`\n  }\n\n  const hashBase64 = await sha256(signatureRaw)\n  const signature = 'v1_' + hashBase64.replace(/=+$/, '')\n\n  return {\n    signature: signature,\n    expiration: signatureExpiration,\n  }\n}\n","import {\n  Client,\n  Code,\n  ConnectError,\n  createClient,\n  Transport,\n} from '@connectrpc/connect'\nimport {\n  ConnectionConfig,\n  ConnectionOpts,\n  defaultUsername,\n  KEEPALIVE_PING_HEADER,\n  KEEPALIVE_PING_INTERVAL_SEC,\n  setupRequestController,\n  Username,\n} from '../../connectionConfig'\n\nimport { handleEnvdApiError, handleWatchDirStartEvent } from '../../envd/api'\nimport { authenticationHeader, handleRpcError } from '../../envd/rpc'\n\nimport { EnvdApiClient } from '../../envd/api'\nimport {\n  Filesystem as FilesystemService,\n  FileType as FsFileType,\n} from '../../envd/filesystem/filesystem_pb'\n\nimport { FilesystemEvent, WatchHandle } from './watchHandle'\n\nimport type { Timestamp } from '@bufbuild/protobuf/wkt'\nimport { compareVersions } from 'compare-versions'\nimport {\n  ENVD_DEFAULT_USER,\n  ENVD_OCTET_STREAM_UPLOAD,\n  ENVD_VERSION_RECURSIVE_WATCH,\n} from '../../envd/versions'\nimport {\n  FileNotFoundError,\n  InvalidArgumentError,\n  TemplateError,\n} from '../../errors'\nimport { toBlob, toUploadBody } from '../../utils'\n\nconst FILESYSTEM_HTTP_ERROR_MAP: Record<number, (message: string) => Error> = {\n  404: (message: string) => new FileNotFoundError(message),\n}\n\nconst FILESYSTEM_RPC_ERROR_MAP: Partial<\n  Record<Code, (message: string) => Error>\n> = {\n  [Code.NotFound]: (message: string) => new FileNotFoundError(message),\n}\n\nfunction handleFilesystemRpcError(err: unknown): Error {\n  return handleRpcError(err, FILESYSTEM_RPC_ERROR_MAP)\n}\n\nfunction handleFilesystemEnvdApiError(res: {\n  error?: { message?: string } | string\n  response: Response\n}) {\n  return handleEnvdApiError(res, FILESYSTEM_HTTP_ERROR_MAP)\n}\n\n/**\n * Sandbox filesystem object information.\n */\nexport interface WriteInfo {\n  /**\n   * Name of the filesystem object.\n   */\n  name: string\n  /**\n   * Type of the filesystem object.\n   */\n  type?: FileType\n  /**\n   * Path to the filesystem object.\n   */\n  path: string\n}\n\nexport interface EntryInfo extends WriteInfo {\n  /**\n   * Size of the filesystem object in bytes.\n   */\n  size: number\n\n  /**\n   * File mode and permission bits.\n   */\n  mode: number\n\n  /**\n   * String representation of file permissions (e.g. 'rwxr-xr-x').\n   */\n  permissions: string\n\n  /**\n   * Owner of the filesystem object.\n   */\n  owner: string\n\n  /**\n   * Group owner of the filesystem object.\n   */\n  group: string\n\n  /**\n   * Last modification time of the filesystem object.\n   */\n  modifiedTime?: Date\n\n  /**\n   * If the filesystem object is a symlink, this is the target of the symlink.\n   */\n  symlinkTarget?: string\n}\n\n/**\n * Sandbox filesystem object type.\n */\nexport enum FileType {\n  /**\n   * Filesystem object is a file.\n   */\n  FILE = 'file',\n  /**\n   * Filesystem object is a directory.\n   */\n  DIR = 'dir',\n}\n\nexport type WriteEntry = {\n  path: string\n  data: string | ArrayBuffer | Blob | ReadableStream\n}\n\nfunction mapFileType(fileType: FsFileType) {\n  switch (fileType) {\n    case FsFileType.DIRECTORY:\n      return FileType.DIR\n    case FsFileType.FILE:\n      return FileType.FILE\n  }\n}\n\nfunction mapModifiedTime(modifiedTime: Timestamp | undefined) {\n  if (!modifiedTime) return undefined\n\n  return new Date(\n    Number(modifiedTime.seconds) * 1000 +\n      Math.floor(modifiedTime.nanos / 1_000_000)\n  )\n}\n\n/**\n * Options for the sandbox filesystem operations.\n */\nexport interface FilesystemRequestOpts\n  extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>> {\n  /**\n   * User to use for the operation in the sandbox.\n   * This affects the resolution of relative paths and ownership of the created filesystem objects.\n   */\n  user?: Username\n}\n\n/**\n * Options for writing files to the sandbox filesystem.\n */\nexport interface FilesystemWriteOpts extends FilesystemRequestOpts {\n  /**\n   * When true, the upload will be gzip-compressed.\n   */\n  gzip?: boolean\n  /**\n   * When true, the upload uses `application/octet-stream` instead of `multipart/form-data`.\n   *\n   * Defaults to `false`. Requires envd 0.5.7 or later — when not supported by\n   * the sandbox's envd version, the upload falls back to `multipart/form-data`.\n   */\n  useOctetStream?: boolean\n}\n\n/**\n * Options for reading files from the sandbox filesystem.\n */\nexport interface FilesystemReadOpts extends FilesystemRequestOpts {\n  /**\n   * When true, the download will request gzip-encoded responses.\n   */\n  gzip?: boolean\n}\n\nexport interface FilesystemListOpts extends FilesystemRequestOpts {\n  /**\n   * Depth of the directory to list.\n   */\n  depth?: number\n}\n\n/**\n * Options for watching a directory.\n */\nexport interface WatchOpts extends FilesystemRequestOpts {\n  /**\n   * Timeout for the watch operation in **milliseconds**.\n   * You can pass `0` to disable the timeout.\n   *\n   * @default 60_000 // 60 seconds\n   */\n  timeoutMs?: number\n  /**\n   * Callback to call when the watch operation stops.\n   */\n  onExit?: (err?: Error) => void | Promise<void>\n  /**\n   * Watch the directory recursively\n   */\n  recursive?: boolean\n}\n\n/**\n * Module for interacting with the sandbox filesystem.\n */\nexport class Filesystem {\n  private readonly rpc: Client<typeof FilesystemService>\n\n  private readonly defaultWatchTimeout = 60_000 // 60 seconds\n  private readonly defaultWatchRecursive = false\n\n  constructor(\n    transport: Transport,\n    private readonly envdApi: EnvdApiClient,\n    private readonly connectionConfig: ConnectionConfig\n  ) {\n    this.rpc = createClient(FilesystemService, transport)\n  }\n\n  /**\n   * Read file content as a `string`.\n   *\n   * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.\n   *\n   * @param path path to the file.\n   * @param opts connection options.\n   * @param [opts.format] format of the file content—`text` by default.\n   *\n   * @returns file content as string\n   */\n  async read(\n    path: string,\n    opts?: FilesystemReadOpts & { format?: 'text' }\n  ): Promise<string>\n  /**\n   * Read file content as a `Uint8Array`.\n   *\n   * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.\n   *\n   * @param path path to the file.\n   * @param opts connection options.\n   * @param [opts.format] format of the file content—`bytes`.\n   *\n   * @returns file content as `Uint8Array`\n   */\n  async read(\n    path: string,\n    opts?: FilesystemReadOpts & { format: 'bytes' }\n  ): Promise<Uint8Array>\n  /**\n   * Read file content as a `Blob`.\n   *\n   * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.\n   *\n   * @param path path to the file.\n   * @param opts connection options.\n   * @param [opts.format] format of the file content—`blob`.\n   *\n   * @returns file content as `Blob`\n   */\n  async read(\n    path: string,\n    opts?: FilesystemReadOpts & { format: 'blob' }\n  ): Promise<Blob>\n  /**\n   * Read file content as a `ReadableStream`.\n   *\n   * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.\n   *\n   * @param path path to the file.\n   * @param opts connection options.\n   * @param [opts.format] format of the file content—`stream`.\n   *\n   * @returns file content as `ReadableStream`\n   */\n  async read(\n    path: string,\n    opts?: FilesystemReadOpts & { format: 'stream' }\n  ): Promise<ReadableStream<Uint8Array>>\n  async read(\n    path: string,\n    opts?: FilesystemReadOpts & {\n      format?: 'text' | 'bytes' | 'blob' | 'stream'\n    }\n  ): Promise<unknown> {\n    const format = opts?.format ?? 'text'\n\n    let user = opts?.user\n    if (\n      user == undefined &&\n      compareVersions(this.envdApi.version, ENVD_DEFAULT_USER) < 0\n    ) {\n      user = defaultUsername\n    }\n\n    const headers: Record<string, string> = {}\n    if (opts?.gzip) {\n      headers['Accept-Encoding'] = 'gzip'\n    }\n\n    const res = await this.envdApi.api.GET('/files', {\n      params: {\n        query: {\n          path,\n          username: user,\n        },\n      },\n      parseAs: format === 'bytes' ? 'arrayBuffer' : format,\n      signal: this.connectionConfig.getSignal(\n        opts?.requestTimeoutMs,\n        opts?.signal\n      ),\n      headers,\n    })\n\n    const err = await handleFilesystemEnvdApiError(res)\n    if (err) {\n      throw err\n    }\n\n    if (format === 'bytes') {\n      return new Uint8Array(res.data as ArrayBuffer)\n    }\n\n    // When the file is empty, res.data is parsed as `{}`. This is a workaround to return an empty string.\n    if (res.response.headers.get('content-length') === '0') {\n      return ''\n    }\n\n    return res.data\n  }\n\n  /**\n   * Write content to a file.\n   *\n   *\n   * Writing to a file that doesn't exist creates the file.\n   *\n   * Writing to a file that already exists overwrites the file.\n   *\n   * Writing to a file at path that doesn't exist creates the necessary directories.\n   *\n   * @param path path to file.\n   * @param data data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`.\n   * @param opts connection options.\n   *\n   * @returns information about the written file\n   */\n  async write(\n    path: string,\n    data: string | ArrayBuffer | Blob | ReadableStream,\n    opts?: FilesystemWriteOpts\n  ): Promise<WriteInfo>\n  async write(\n    files: WriteEntry[],\n    opts?: FilesystemWriteOpts\n  ): Promise<WriteInfo[]>\n  async write(\n    pathOrFiles: string | WriteEntry[],\n    dataOrOpts?:\n      | string\n      | ArrayBuffer\n      | Blob\n      | ReadableStream\n      | FilesystemWriteOpts,\n    opts?: FilesystemWriteOpts\n  ): Promise<WriteInfo | WriteInfo[]> {\n    if (typeof pathOrFiles !== 'string' && !Array.isArray(pathOrFiles)) {\n      throw new Error('Path or files are required')\n    }\n\n    if (typeof pathOrFiles === 'string' && Array.isArray(dataOrOpts)) {\n      throw new Error(\n        'Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files.'\n      )\n    }\n\n    const { path, writeOpts, writeFiles } =\n      typeof pathOrFiles === 'string'\n        ? {\n            path: pathOrFiles,\n            writeOpts: opts as FilesystemWriteOpts,\n            writeFiles: [\n              {\n                data: dataOrOpts as\n                  | string\n                  | ArrayBuffer\n                  | Blob\n                  | ReadableStream,\n              },\n            ],\n          }\n        : {\n            path: undefined,\n            writeOpts: dataOrOpts as FilesystemWriteOpts,\n            writeFiles: pathOrFiles as WriteEntry[],\n          }\n\n    if (writeFiles.length === 0) return [] as WriteInfo[]\n\n    let user = writeOpts?.user\n    if (\n      user == undefined &&\n      compareVersions(this.envdApi.version, ENVD_DEFAULT_USER) < 0\n    ) {\n      user = defaultUsername\n    }\n\n    const supportsOctetStream =\n      compareVersions(this.envdApi.version, ENVD_OCTET_STREAM_UPLOAD) >= 0\n    const useOctetStream =\n      (writeOpts?.useOctetStream ?? false) && supportsOctetStream\n\n    const results: WriteInfo[] = []\n\n    const useGzip = writeOpts?.gzip === true\n\n    if (useOctetStream) {\n      const headers: Record<string, string> = {\n        'Content-Type': 'application/octet-stream',\n      }\n      if (useGzip) {\n        headers['Content-Encoding'] = 'gzip'\n      }\n\n      const uploadResults = await Promise.all(\n        writeFiles.map(async (file) => {\n          const filePath = path ?? (file as WriteEntry).path\n          const body = await toUploadBody(file.data, useGzip)\n\n          const res = await this.envdApi.api.POST('/files', {\n            params: {\n              query: {\n                path: filePath,\n                username: user,\n              },\n            },\n            bodySerializer: () => body,\n            headers,\n            signal: this.connectionConfig.getSignal(\n              writeOpts?.requestTimeoutMs,\n              writeOpts?.signal\n            ),\n            body: {},\n          })\n\n          const err = await handleFilesystemEnvdApiError(res)\n          if (err) {\n            throw err\n          }\n\n          const files = res.data as WriteInfo[]\n          if (!files || files.length === 0) {\n            throw new Error(\n              'Expected to receive information about written file'\n            )\n          }\n\n          return files\n        })\n      )\n\n      for (const files of uploadResults) {\n        results.push(...files)\n      }\n    } else {\n      const formData = new FormData()\n      for (const file of writeFiles) {\n        formData.append(\n          'file',\n          await toBlob(file.data),\n          (file as WriteEntry).path ?? path!\n        )\n      }\n\n      const res = await this.envdApi.api.POST('/files', {\n        params: {\n          query: {\n            path,\n            username: user,\n          },\n        },\n        bodySerializer: () => formData,\n        signal: this.connectionConfig.getSignal(\n          writeOpts?.requestTimeoutMs,\n          writeOpts?.signal\n        ),\n        body: {},\n      })\n\n      const err = await handleFilesystemEnvdApiError(res)\n      if (err) {\n        throw err\n      }\n\n      const files = res.data as WriteInfo[]\n      if (!files || files.length === 0) {\n        throw new Error('Expected to receive information about written file')\n      }\n\n      results.push(...files)\n    }\n\n    return results.length === 1 && path ? results[0] : results\n  }\n\n  /**\n   * Write multiple files.\n   *\n   *\n   * Writing to a file that doesn't exist creates the file.\n   *\n   * Writing to a file that already exists overwrites the file.\n   *\n   * Writing to a file at path that doesn't exist creates the necessary directories.\n   *\n   * @param files list of files to write as `WriteEntry` objects, each containing `path` and `data`.\n   * @param opts connection options.\n   *\n   * @returns information about the written files\n   */\n  async writeFiles(\n    files: WriteEntry[],\n    opts?: FilesystemWriteOpts\n  ): Promise<WriteInfo[]> {\n    return this.write(files, opts) as Promise<WriteInfo[]>\n  }\n\n  /**\n   * List entries in a directory.\n   *\n   * @param path path to the directory.\n   * @param opts connection options.\n   *\n   * @returns list of entries in the sandbox filesystem directory.\n   */\n  async list(path: string, opts?: FilesystemListOpts): Promise<EntryInfo[]> {\n    if (typeof opts?.depth === 'number' && opts.depth < 1) {\n      throw new InvalidArgumentError('depth should be at least one')\n    }\n\n    try {\n      const res = await this.rpc.listDir(\n        {\n          path,\n          depth: opts?.depth ?? 1,\n        },\n        {\n          headers: authenticationHeader(this.envdApi.version, opts?.user),\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n\n      const entries: EntryInfo[] = []\n\n      for (const e of res.entries) {\n        const type = mapFileType(e.type)\n\n        if (type) {\n          entries.push({\n            name: e.name,\n            type,\n            path: e.path,\n            size: Number(e.size),\n            mode: e.mode,\n            permissions: e.permissions,\n            owner: e.owner,\n            group: e.group,\n            modifiedTime: mapModifiedTime(e.modifiedTime),\n            symlinkTarget: e.symlinkTarget,\n          })\n        }\n      }\n\n      return entries\n    } catch (err) {\n      throw handleFilesystemRpcError(err)\n    }\n  }\n\n  /**\n   * Create a new directory and all directories along the way if needed on the specified path.\n   *\n   * @param path path to a new directory. For example '/dirA/dirB' when creating 'dirB'.\n   * @param opts connection options.\n   *\n   * @returns `true` if the directory was created, `false` if it already exists.\n   */\n  async makeDir(path: string, opts?: FilesystemRequestOpts): Promise<boolean> {\n    try {\n      await this.rpc.makeDir(\n        { path },\n        {\n          headers: authenticationHeader(this.envdApi.version, opts?.user),\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n\n      return true\n    } catch (err) {\n      if (err instanceof ConnectError) {\n        if (err.code === Code.AlreadyExists) {\n          return false\n        }\n      }\n\n      throw handleFilesystemRpcError(err)\n    }\n  }\n\n  /**\n   * Rename a file or directory.\n   *\n   * @param oldPath path to the file or directory to rename.\n   * @param newPath new path for the file or directory.\n   * @param opts connection options.\n   *\n   * @returns information about renamed file or directory.\n   */\n  async rename(\n    oldPath: string,\n    newPath: string,\n    opts?: FilesystemRequestOpts\n  ): Promise<EntryInfo> {\n    try {\n      const res = await this.rpc.move(\n        {\n          source: oldPath,\n          destination: newPath,\n        },\n        {\n          headers: authenticationHeader(this.envdApi.version, opts?.user),\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n\n      const entry = res.entry\n      if (!entry) {\n        throw new Error('Expected to receive information about moved object')\n      }\n\n      return {\n        name: entry.name,\n        type: mapFileType(entry.type),\n        path: entry.path,\n        size: Number(entry.size),\n        mode: entry.mode,\n        permissions: entry.permissions,\n        owner: entry.owner,\n        group: entry.group,\n        modifiedTime: mapModifiedTime(entry.modifiedTime),\n        symlinkTarget: entry.symlinkTarget,\n      }\n    } catch (err) {\n      throw handleFilesystemRpcError(err)\n    }\n  }\n\n  /**\n   * Remove a file or directory.\n   *\n   * @param path path to a file or directory.\n   * @param opts connection options.\n   */\n  async remove(path: string, opts?: FilesystemRequestOpts): Promise<void> {\n    try {\n      await this.rpc.remove(\n        { path },\n        {\n          headers: authenticationHeader(this.envdApi.version, opts?.user),\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n    } catch (err) {\n      throw handleFilesystemRpcError(err)\n    }\n  }\n\n  /**\n   * Check if a file or a directory exists.\n   *\n   * @param path path to a file or a directory\n   * @param opts connection options.\n   *\n   * @returns `true` if the file or directory exists, `false` otherwise\n   */\n  async exists(path: string, opts?: FilesystemRequestOpts): Promise<boolean> {\n    try {\n      await this.rpc.stat(\n        { path },\n        {\n          headers: authenticationHeader(this.envdApi.version, opts?.user),\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n\n      return true\n    } catch (err) {\n      if (err instanceof ConnectError) {\n        if (err.code === Code.NotFound) {\n          return false\n        }\n      }\n\n      throw handleFilesystemRpcError(err)\n    }\n  }\n\n  /**\n   * Get information about a file or directory.\n   *\n   * @param path path to a file or directory.\n   * @param opts connection options.\n   *\n   * @returns information about the file or directory like name, type, and path.\n   */\n  async getInfo(\n    path: string,\n    opts?: FilesystemRequestOpts\n  ): Promise<EntryInfo> {\n    try {\n      const res = await this.rpc.stat(\n        { path },\n        {\n          headers: authenticationHeader(this.envdApi.version, opts?.user),\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n\n      if (!res.entry) {\n        throw new Error(\n          'Expected to receive information about the file or directory'\n        )\n      }\n\n      return {\n        name: res.entry.name,\n        type: mapFileType(res.entry.type),\n        path: res.entry.path,\n        size: Number(res.entry.size),\n        mode: res.entry.mode,\n        permissions: res.entry.permissions,\n        owner: res.entry.owner,\n        group: res.entry.group,\n        modifiedTime: mapModifiedTime(res.entry.modifiedTime),\n        symlinkTarget: res.entry.symlinkTarget,\n      }\n    } catch (err) {\n      throw handleFilesystemRpcError(err)\n    }\n  }\n\n  /**\n   * Start watching a directory for filesystem events.\n   *\n   * @param path path to directory to watch.\n   * @param onEvent callback to call when an event in the directory occurs.\n   * @param opts connection options.\n   *\n   * @returns `WatchHandle` object for stopping watching directory.\n   */\n  async watchDir(\n    path: string,\n    onEvent: (event: FilesystemEvent) => void | Promise<void>,\n    opts?: WatchOpts & {\n      onExit?: (err?: Error) => void | Promise<void>\n    }\n  ): Promise<WatchHandle> {\n    if (\n      opts?.recursive &&\n      this.envdApi.version &&\n      compareVersions(this.envdApi.version, ENVD_VERSION_RECURSIVE_WATCH) < 0\n    ) {\n      throw new TemplateError(\n        'You need to update the template to use recursive watching. ' +\n          'You can do this by running `e2b template build` in the directory with the template.'\n      )\n    }\n\n    const requestTimeoutMs =\n      opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n    const { controller, clearStartTimeout, cleanup } = setupRequestController(\n      requestTimeoutMs,\n      opts?.signal\n    )\n\n    const events = this.rpc.watchDir(\n      {\n        path,\n        recursive: opts?.recursive ?? this.defaultWatchRecursive,\n      },\n      {\n        headers: {\n          ...authenticationHeader(this.envdApi.version, opts?.user),\n          [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),\n        },\n        signal: controller.signal,\n        timeoutMs: opts?.timeoutMs ?? this.defaultWatchTimeout,\n      }\n    )\n\n    try {\n      await handleWatchDirStartEvent(events)\n      clearStartTimeout()\n\n      return new WatchHandle(cleanup, events, onEvent, opts?.onExit)\n    } catch (err) {\n      cleanup()\n      throw handleFilesystemRpcError(err)\n    }\n  }\n}\n","import createClient from 'openapi-fetch'\n\nimport type { components, paths } from './schema.gen'\nimport { ConnectionConfig } from '../connectionConfig'\nimport { createApiLogger } from '../logs'\nimport {\n  SandboxError,\n  InvalidArgumentError,\n  NotFoundError,\n  NotEnoughSpaceError,\n  SandboxNotFoundError,\n  formatSandboxTimeoutError,\n  AuthenticationError,\n} from '../errors'\nimport { StartResponse, ConnectResponse } from './process/process_pb'\nimport { Code, ConnectError } from '@connectrpc/connect'\nimport { WatchDirResponse } from './filesystem/filesystem_pb'\n\ntype ApiError = { message?: string } | string\n\nconst DEFAULT_ERROR_MAP: Record<number, (message: string) => Error> = {\n  400: (message) => new InvalidArgumentError(message),\n  401: (message) => new AuthenticationError(message),\n  404: (message) => new NotFoundError(message),\n  429: (message) =>\n    new SandboxError(`${message}: The requests are being rate limited.`),\n  502: formatSandboxTimeoutError,\n  507: (message) => new NotEnoughSpaceError(message),\n}\n\n/**\n * Handles errors from envd API responses by mapping HTTP status codes to specific error types.\n *\n * @param res - The API response object containing an optional error and the raw `Response`.\n * @param errorMap - Optional map of HTTP status codes to error factory functions that override the defaults.\n * @returns The corresponding `Error` instance if an error is present, or `undefined` if the response is successful.\n */\nexport async function handleEnvdApiError(\n  res: {\n    error?: ApiError\n    response: Response\n  },\n  errorMap?: Record<number, (message: string) => Error>\n) {\n  if (!res.error) {\n    return\n  }\n\n  const message: string =\n    typeof res.error == 'string'\n      ? res.error\n      : res.error?.message || (await res.response.text())\n\n  // Check if a custom error mapping is provided for this error code\n  if (errorMap && res.response.status in errorMap) {\n    return errorMap[res.response.status]?.(message)\n  }\n\n  // Check if there is a default error mapping for this error code\n  if (res.response.status in DEFAULT_ERROR_MAP) {\n    return DEFAULT_ERROR_MAP[res.response.status]?.(message)\n  }\n\n  // Fallback to a generic SandboxError if no specific mapping is found\n  return new SandboxError(`${res.response.status}: ${message}`)\n}\n\nexport async function handleProcessStartEvent(\n  events: AsyncIterable<StartResponse | ConnectResponse>\n) {\n  let startEvent: StartResponse | ConnectResponse\n\n  try {\n    startEvent = (await events[Symbol.asyncIterator]().next()).value\n  } catch (err) {\n    if (err instanceof ConnectError) {\n      if (err.code === Code.Unavailable) {\n        throw new SandboxNotFoundError(\n          'Sandbox is probably not running anymore'\n        )\n      }\n    }\n\n    throw err\n  }\n  if (startEvent.event?.event.case !== 'start') {\n    throw new Error('Expected start event')\n  }\n\n  return startEvent.event.event.value.pid\n}\n\nexport async function handleWatchDirStartEvent(\n  events: AsyncIterable<WatchDirResponse>\n) {\n  let startEvent: WatchDirResponse\n\n  try {\n    startEvent = (await events[Symbol.asyncIterator]().next()).value\n  } catch (err) {\n    if (err instanceof ConnectError) {\n      if (err.code === Code.Unavailable) {\n        throw new SandboxNotFoundError(\n          'Sandbox is probably not running anymore'\n        )\n      }\n    }\n\n    throw err\n  }\n  if (startEvent.event?.case !== 'start') {\n    throw new Error('Expected start event')\n  }\n\n  return startEvent.event.value\n}\n\nclass EnvdApiClient {\n  readonly api: ReturnType<typeof createClient<paths>>\n  readonly version: string\n\n  constructor(\n    config: Pick<ConnectionConfig, 'apiUrl' | 'logger' | 'accessToken'> & {\n      fetch?: (request: Request) => ReturnType<typeof fetch>\n      headers?: Record<string, string>\n    },\n    metadata: {\n      version: string\n    }\n  ) {\n    this.api = createClient({\n      baseUrl: config.apiUrl,\n      fetch: config?.fetch,\n      headers: config?.headers,\n      // In HTTP 1.1, all connections are considered persistent unless declared otherwise\n      // keepalive: true,\n    })\n    this.version = metadata.version\n\n    if (config.logger) {\n      this.api.use(createApiLogger(config.logger))\n    }\n  }\n}\n\nexport type { components, paths }\nexport { EnvdApiClient }\n","import { Code, ConnectError } from '@connectrpc/connect'\nimport { runtime } from '../utils'\n\nimport { compareVersions } from 'compare-versions'\nimport { defaultUsername } from '../connectionConfig'\nimport {\n  AuthenticationError,\n  formatSandboxTimeoutError,\n  InvalidArgumentError,\n  NotFoundError,\n  SandboxError,\n  TimeoutError,\n} from '../errors'\nimport { ENVD_DEFAULT_USER } from './versions'\n\nconst DEFAULT_ERROR_MAP: Partial<Record<Code, (message: string) => Error>> = {\n  [Code.InvalidArgument]: (message) => new InvalidArgumentError(message),\n  [Code.Unauthenticated]: (message) => new AuthenticationError(message),\n  [Code.NotFound]: (message) => new NotFoundError(message),\n  [Code.Unavailable]: formatSandboxTimeoutError,\n  [Code.Canceled]: (message) =>\n    new TimeoutError(\n      `${message}: This error is likely due to exceeding 'requestTimeoutMs'. You can pass the request timeout value as an option when making the request.`\n    ),\n  [Code.DeadlineExceeded]: (message) =>\n    new TimeoutError(\n      `${message}: This error is likely due to exceeding 'timeoutMs' — the total time a long running request (like command execution or directory watch) can be active. It can be modified by passing 'timeoutMs' when making the request. Use '0' to disable the timeout.`\n    ),\n}\n\n/**\n * Handles errors from envd RPC calls by mapping gRPC status codes to specific error types.\n *\n * @param err - The caught error, expected to be a `ConnectError` from the gRPC transport.\n * @param errorMap - Optional map of gRPC `Code` values to error factory functions that override the defaults.\n * @returns The corresponding `Error` instance mapped from the gRPC status code, or the original error if it is not a `ConnectError`.\n */\nexport function handleRpcError(\n  err: unknown,\n  errorMap?: Partial<Record<Code, (message: string) => Error>>\n): Error {\n  if (err instanceof ConnectError) {\n    // Check if a custom error mapping is provided for this error code\n    if (errorMap && err.code in errorMap) {\n      return errorMap[err.code]!(err.message)\n    }\n\n    // Check if there is a default error mapping for this error code\n    if (err.code in DEFAULT_ERROR_MAP) {\n      return DEFAULT_ERROR_MAP[err.code]!(err.message)\n    }\n\n    // Fallback to a generic SandboxError if no specific mapping is found\n    return new SandboxError(`${err.code}: ${err.message}`)\n  }\n\n  return err as Error\n}\n\nfunction encode64(value: string): string {\n  switch (runtime) {\n    case 'deno':\n      return btoa(value)\n    case 'node':\n      return Buffer.from(value).toString('base64')\n    case 'bun':\n      return Buffer.from(value).toString('base64')\n    default:\n      return btoa(value)\n  }\n}\n\nexport function authenticationHeader(\n  envdVersion: string,\n  username: string | undefined\n): Record<string, string> {\n  if (\n    username == undefined &&\n    compareVersions(envdVersion, ENVD_DEFAULT_USER) < 0\n  ) {\n    username = defaultUsername\n  }\n\n  if (!username) {\n    return {}\n  }\n\n  const value = `${username}:`\n\n  const encoded = encode64(value)\n\n  return { Authorization: `Basic ${encoded}` }\n}\n","export const ENVD_VERSION_RECURSIVE_WATCH = '0.1.4'\nexport const ENVD_DEBUG_FALLBACK = '99.99.99'\nexport const ENVD_COMMANDS_STDIN = '0.3.0'\nexport const ENVD_DEFAULT_USER = '0.4.0'\nexport const ENVD_ENVD_CLOSE = '0.5.2'\nexport const ENVD_OCTET_STREAM_UPLOAD = '0.5.7'\n","// @generated by protoc-gen-es v2.6.2 with parameter \"target=ts\"\n// @generated from file filesystem/filesystem.proto (package filesystem, syntax proto3)\n/* eslint-disable */\n\nimport type {\n  GenEnum,\n  GenFile,\n  GenMessage,\n  GenService,\n} from '@bufbuild/protobuf/codegenv2'\nimport {\n  enumDesc,\n  fileDesc,\n  messageDesc,\n  serviceDesc,\n} from '@bufbuild/protobuf/codegenv2'\nimport type { Timestamp } from '@bufbuild/protobuf/wkt'\nimport { file_google_protobuf_timestamp } from '@bufbuild/protobuf/wkt'\nimport type { Message } from '@bufbuild/protobuf'\n\n/**\n * Describes the file filesystem/filesystem.proto.\n */\nexport const file_filesystem_filesystem: GenFile =\n  /*@__PURE__*/\n  fileDesc(\n    'ChtmaWxlc3lzdGVtL2ZpbGVzeXN0ZW0ucHJvdG8SCmZpbGVzeXN0ZW0iMgoLTW92ZVJlcXVlc3QSDgoGc291cmNlGAEgASgJEhMKC2Rlc3RpbmF0aW9uGAIgASgJIjQKDE1vdmVSZXNwb25zZRIkCgVlbnRyeRgBIAEoCzIVLmZpbGVzeXN0ZW0uRW50cnlJbmZvIh4KDk1ha2VEaXJSZXF1ZXN0EgwKBHBhdGgYASABKAkiNwoPTWFrZURpclJlc3BvbnNlEiQKBWVudHJ5GAEgASgLMhUuZmlsZXN5c3RlbS5FbnRyeUluZm8iHQoNUmVtb3ZlUmVxdWVzdBIMCgRwYXRoGAEgASgJIhAKDlJlbW92ZVJlc3BvbnNlIhs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BvbnNlEj8KBlJlbW92ZRIZLmZpbGVzeXN0ZW0uUmVtb3ZlUmVxdWVzdBoaLmZpbGVzeXN0ZW0uUmVtb3ZlUmVzcG9uc2USRwoIV2F0Y2hEaXISGy5maWxlc3lzdGVtLldhdGNoRGlyUmVxdWVzdBocLmZpbGVzeXN0ZW0uV2F0Y2hEaXJSZXNwb25zZTABElQKDUNyZWF0ZVdhdGNoZXISIC5maWxlc3lzdGVtLkNyZWF0ZVdhdGNoZXJSZXF1ZXN0GiEuZmlsZXN5c3RlbS5DcmVhdGVXYXRjaGVyUmVzcG9uc2USXQoQR2V0V2F0Y2hlckV2ZW50cxIjLmZpbGVzeXN0ZW0uR2V0V2F0Y2hlckV2ZW50c1JlcXVlc3QaJC5maWxlc3lzdGVtLkdldFdhdGNoZXJFdmVudHNSZXNwb25zZRJUCg1SZW1vdmVXYXRjaGVyEiAuZmlsZXN5c3RlbS5SZW1vdmVXYXRjaGVyUmVxdWVzdBohLmZpbGVzeXN0ZW0uUmVtb3ZlV2F0Y2hlclJlc3BvbnNlQmkKDmNvbS5maWxlc3lzdGVtQg9GaWxlc3lzdGVtUHJvdG9QAaICA0ZYWKoCCkZpbGVzeXN0ZW3KAgpGaWxlc3lzdGVt4gIWRmlsZXN5c3RlbVxHUEJNZXRhZGF0YeoCCkZpbGVzeXN0ZW1iBnByb3RvMw',\n    [file_google_protobuf_timestamp]\n  )\n\n/**\n * @generated from message filesystem.MoveRequest\n */\nexport type MoveRequest = Message<'filesystem.MoveRequest'> & {\n  /**\n   * @generated from field: string source = 1;\n   */\n  source: string\n\n  /**\n   * @generated from field: string destination = 2;\n   */\n  destination: string\n}\n\n/**\n * Describes the message filesystem.MoveRequest.\n * Use `create(MoveRequestSchema)` to create a new message.\n */\nexport const MoveRequestSchema: GenMessage<MoveRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 0)\n\n/**\n * @generated from message filesystem.MoveResponse\n */\nexport type MoveResponse = Message<'filesystem.MoveResponse'> & {\n  /**\n   * @generated from field: filesystem.EntryInfo entry = 1;\n   */\n  entry?: EntryInfo\n}\n\n/**\n * Describes the message filesystem.MoveResponse.\n * Use `create(MoveResponseSchema)` to create a new message.\n */\nexport const MoveResponseSchema: GenMessage<MoveResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 1)\n\n/**\n * @generated from message filesystem.MakeDirRequest\n */\nexport type MakeDirRequest = Message<'filesystem.MakeDirRequest'> & {\n  /**\n   * @generated from field: string path = 1;\n   */\n  path: string\n}\n\n/**\n * Describes the message filesystem.MakeDirRequest.\n * Use `create(MakeDirRequestSchema)` to create a new message.\n */\nexport const MakeDirRequestSchema: GenMessage<MakeDirRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 2)\n\n/**\n * @generated from message filesystem.MakeDirResponse\n */\nexport type MakeDirResponse = Message<'filesystem.MakeDirResponse'> & {\n  /**\n   * @generated from field: filesystem.EntryInfo entry = 1;\n   */\n  entry?: EntryInfo\n}\n\n/**\n * Describes the message filesystem.MakeDirResponse.\n * Use `create(MakeDirResponseSchema)` to create a new message.\n */\nexport const MakeDirResponseSchema: GenMessage<MakeDirResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 3)\n\n/**\n * @generated from message filesystem.RemoveRequest\n */\nexport type RemoveRequest = Message<'filesystem.RemoveRequest'> & {\n  /**\n   * @generated from field: string path = 1;\n   */\n  path: string\n}\n\n/**\n * Describes the message filesystem.RemoveRequest.\n * Use `create(RemoveRequestSchema)` to create a new message.\n */\nexport const RemoveRequestSchema: GenMessage<RemoveRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 4)\n\n/**\n * @generated from message filesystem.RemoveResponse\n */\nexport type RemoveResponse = Message<'filesystem.RemoveResponse'> & {}\n\n/**\n * Describes the message filesystem.RemoveResponse.\n * Use `create(RemoveResponseSchema)` to create a new message.\n */\nexport const RemoveResponseSchema: GenMessage<RemoveResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 5)\n\n/**\n * @generated from message filesystem.StatRequest\n */\nexport type StatRequest = Message<'filesystem.StatRequest'> & {\n  /**\n   * @generated from field: string path = 1;\n   */\n  path: string\n}\n\n/**\n * Describes the message filesystem.StatRequest.\n * Use `create(StatRequestSchema)` to create a new message.\n */\nexport const StatRequestSchema: GenMessage<StatRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 6)\n\n/**\n * @generated from message filesystem.StatResponse\n */\nexport type StatResponse = Message<'filesystem.StatResponse'> & {\n  /**\n   * @generated from field: filesystem.EntryInfo entry = 1;\n   */\n  entry?: EntryInfo\n}\n\n/**\n * Describes the message filesystem.StatResponse.\n * Use `create(StatResponseSchema)` to create a new message.\n */\nexport const StatResponseSchema: GenMessage<StatResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 7)\n\n/**\n * @generated from message filesystem.EntryInfo\n */\nexport type EntryInfo = Message<'filesystem.EntryInfo'> & {\n  /**\n   * @generated from field: string name = 1;\n   */\n  name: string\n\n  /**\n   * @generated from field: filesystem.FileType type = 2;\n   */\n  type: FileType\n\n  /**\n   * @generated from field: string path = 3;\n   */\n  path: string\n\n  /**\n   * @generated from field: int64 size = 4;\n   */\n  size: bigint\n\n  /**\n   * @generated from field: uint32 mode = 5;\n   */\n  mode: number\n\n  /**\n   * @generated from field: string permissions = 6;\n   */\n  permissions: string\n\n  /**\n   * @generated from field: string owner = 7;\n   */\n  owner: string\n\n  /**\n   * @generated from field: string group = 8;\n   */\n  group: string\n\n  /**\n   * @generated from field: google.protobuf.Timestamp modified_time = 9;\n   */\n  modifiedTime?: Timestamp\n\n  /**\n   * If the entry is a symlink, this field contains the target of the symlink.\n   *\n   * @generated from field: optional string symlink_target = 10;\n   */\n  symlinkTarget?: string\n}\n\n/**\n * Describes the message filesystem.EntryInfo.\n * Use `create(EntryInfoSchema)` to create a new message.\n */\nexport const EntryInfoSchema: GenMessage<EntryInfo> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 8)\n\n/**\n * @generated from message filesystem.ListDirRequest\n */\nexport type ListDirRequest = Message<'filesystem.ListDirRequest'> & {\n  /**\n   * @generated from field: string path = 1;\n   */\n  path: string\n\n  /**\n   * @generated from field: uint32 depth = 2;\n   */\n  depth: number\n}\n\n/**\n * Describes the message filesystem.ListDirRequest.\n * Use `create(ListDirRequestSchema)` to create a new message.\n */\nexport const ListDirRequestSchema: GenMessage<ListDirRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 9)\n\n/**\n * @generated from message filesystem.ListDirResponse\n */\nexport type ListDirResponse = Message<'filesystem.ListDirResponse'> & {\n  /**\n   * @generated from field: repeated filesystem.EntryInfo entries = 1;\n   */\n  entries: EntryInfo[]\n}\n\n/**\n * Describes the message filesystem.ListDirResponse.\n * Use `create(ListDirResponseSchema)` to create a new message.\n */\nexport const ListDirResponseSchema: GenMessage<ListDirResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 10)\n\n/**\n * @generated from message filesystem.WatchDirRequest\n */\nexport type WatchDirRequest = Message<'filesystem.WatchDirRequest'> & {\n  /**\n   * @generated from field: string path = 1;\n   */\n  path: string\n\n  /**\n   * @generated from field: bool recursive = 2;\n   */\n  recursive: boolean\n}\n\n/**\n * Describes the message filesystem.WatchDirRequest.\n * Use `create(WatchDirRequestSchema)` to create a new message.\n */\nexport const WatchDirRequestSchema: GenMessage<WatchDirRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 11)\n\n/**\n * @generated from message filesystem.FilesystemEvent\n */\nexport type FilesystemEvent = Message<'filesystem.FilesystemEvent'> & {\n  /**\n   * @generated from field: string name = 1;\n   */\n  name: string\n\n  /**\n   * @generated from field: filesystem.EventType type = 2;\n   */\n  type: EventType\n}\n\n/**\n * Describes the message filesystem.FilesystemEvent.\n * Use `create(FilesystemEventSchema)` to create a new message.\n */\nexport const FilesystemEventSchema: GenMessage<FilesystemEvent> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 12)\n\n/**\n * @generated from message filesystem.WatchDirResponse\n */\nexport type WatchDirResponse = Message<'filesystem.WatchDirResponse'> & {\n  /**\n   * @generated from oneof filesystem.WatchDirResponse.event\n   */\n  event:\n    | {\n        /**\n         * @generated from field: filesystem.WatchDirResponse.StartEvent start = 1;\n         */\n        value: WatchDirResponse_StartEvent\n        case: 'start'\n      }\n    | {\n        /**\n         * @generated from field: filesystem.FilesystemEvent filesystem = 2;\n         */\n        value: FilesystemEvent\n        case: 'filesystem'\n      }\n    | {\n        /**\n         * @generated from field: filesystem.WatchDirResponse.KeepAlive keepalive = 3;\n         */\n        value: WatchDirResponse_KeepAlive\n        case: 'keepalive'\n      }\n    | { case: undefined; value?: undefined }\n}\n\n/**\n * Describes the message filesystem.WatchDirResponse.\n * Use `create(WatchDirResponseSchema)` to create a new message.\n */\nexport const WatchDirResponseSchema: GenMessage<WatchDirResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 13)\n\n/**\n * @generated from message filesystem.WatchDirResponse.StartEvent\n */\nexport type WatchDirResponse_StartEvent =\n  Message<'filesystem.WatchDirResponse.StartEvent'> & {}\n\n/**\n * Describes the message filesystem.WatchDirResponse.StartEvent.\n * Use `create(WatchDirResponse_StartEventSchema)` to create a new message.\n */\nexport const WatchDirResponse_StartEventSchema: GenMessage<WatchDirResponse_StartEvent> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 13, 0)\n\n/**\n * @generated from message filesystem.WatchDirResponse.KeepAlive\n */\nexport type WatchDirResponse_KeepAlive =\n  Message<'filesystem.WatchDirResponse.KeepAlive'> & {}\n\n/**\n * Describes the message filesystem.WatchDirResponse.KeepAlive.\n * Use `create(WatchDirResponse_KeepAliveSchema)` to create a new message.\n */\nexport const WatchDirResponse_KeepAliveSchema: GenMessage<WatchDirResponse_KeepAlive> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 13, 1)\n\n/**\n * @generated from message filesystem.CreateWatcherRequest\n */\nexport type CreateWatcherRequest =\n  Message<'filesystem.CreateWatcherRequest'> & {\n    /**\n     * @generated from field: string path = 1;\n     */\n    path: string\n\n    /**\n     * @generated from field: bool recursive = 2;\n     */\n    recursive: boolean\n  }\n\n/**\n * Describes the message filesystem.CreateWatcherRequest.\n * Use `create(CreateWatcherRequestSchema)` to create a new message.\n */\nexport const CreateWatcherRequestSchema: GenMessage<CreateWatcherRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 14)\n\n/**\n * @generated from message filesystem.CreateWatcherResponse\n */\nexport type CreateWatcherResponse =\n  Message<'filesystem.CreateWatcherResponse'> & {\n    /**\n     * @generated from field: string watcher_id = 1;\n     */\n    watcherId: string\n  }\n\n/**\n * Describes the message filesystem.CreateWatcherResponse.\n * Use `create(CreateWatcherResponseSchema)` to create a new message.\n */\nexport const CreateWatcherResponseSchema: GenMessage<CreateWatcherResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 15)\n\n/**\n * @generated from message filesystem.GetWatcherEventsRequest\n */\nexport type GetWatcherEventsRequest =\n  Message<'filesystem.GetWatcherEventsRequest'> & {\n    /**\n     * @generated from field: string watcher_id = 1;\n     */\n    watcherId: string\n  }\n\n/**\n * Describes the message filesystem.GetWatcherEventsRequest.\n * Use `create(GetWatcherEventsRequestSchema)` to create a new message.\n */\nexport const GetWatcherEventsRequestSchema: GenMessage<GetWatcherEventsRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 16)\n\n/**\n * @generated from message filesystem.GetWatcherEventsResponse\n */\nexport type GetWatcherEventsResponse =\n  Message<'filesystem.GetWatcherEventsResponse'> & {\n    /**\n     * @generated from field: repeated filesystem.FilesystemEvent events = 1;\n     */\n    events: FilesystemEvent[]\n  }\n\n/**\n * Describes the message filesystem.GetWatcherEventsResponse.\n * Use `create(GetWatcherEventsResponseSchema)` to create a new message.\n */\nexport const GetWatcherEventsResponseSchema: GenMessage<GetWatcherEventsResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 17)\n\n/**\n * @generated from message filesystem.RemoveWatcherRequest\n */\nexport type RemoveWatcherRequest =\n  Message<'filesystem.RemoveWatcherRequest'> & {\n    /**\n     * @generated from field: string watcher_id = 1;\n     */\n    watcherId: string\n  }\n\n/**\n * Describes the message filesystem.RemoveWatcherRequest.\n * Use `create(RemoveWatcherRequestSchema)` to create a new message.\n */\nexport const RemoveWatcherRequestSchema: GenMessage<RemoveWatcherRequest> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 18)\n\n/**\n * @generated from message filesystem.RemoveWatcherResponse\n */\nexport type RemoveWatcherResponse =\n  Message<'filesystem.RemoveWatcherResponse'> & {}\n\n/**\n * Describes the message filesystem.RemoveWatcherResponse.\n * Use `create(RemoveWatcherResponseSchema)` to create a new message.\n */\nexport const RemoveWatcherResponseSchema: GenMessage<RemoveWatcherResponse> =\n  /*@__PURE__*/\n  messageDesc(file_filesystem_filesystem, 19)\n\n/**\n * @generated from enum filesystem.FileType\n */\nexport enum FileType {\n  /**\n   * @generated from enum value: FILE_TYPE_UNSPECIFIED = 0;\n   */\n  UNSPECIFIED = 0,\n\n  /**\n   * @generated from enum value: FILE_TYPE_FILE = 1;\n   */\n  FILE = 1,\n\n  /**\n   * @generated from enum value: FILE_TYPE_DIRECTORY = 2;\n   */\n  DIRECTORY = 2,\n}\n\n/**\n * Describes the enum filesystem.FileType.\n */\nexport const FileTypeSchema: GenEnum<FileType> =\n  /*@__PURE__*/\n  enumDesc(file_filesystem_filesystem, 0)\n\n/**\n * @generated from enum filesystem.EventType\n */\nexport enum EventType {\n  /**\n   * @generated from enum value: EVENT_TYPE_UNSPECIFIED = 0;\n   */\n  UNSPECIFIED = 0,\n\n  /**\n   * @generated from enum value: EVENT_TYPE_CREATE = 1;\n   */\n  CREATE = 1,\n\n  /**\n   * @generated from enum value: EVENT_TYPE_WRITE = 2;\n   */\n  WRITE = 2,\n\n  /**\n   * @generated from enum value: EVENT_TYPE_REMOVE = 3;\n   */\n  REMOVE = 3,\n\n  /**\n   * @generated from enum value: EVENT_TYPE_RENAME = 4;\n   */\n  RENAME = 4,\n\n  /**\n   * @generated from enum value: EVENT_TYPE_CHMOD = 5;\n   */\n  CHMOD = 5,\n}\n\n/**\n * Describes the enum filesystem.EventType.\n */\nexport const EventTypeSchema: GenEnum<EventType> =\n  /*@__PURE__*/\n  enumDesc(file_filesystem_filesystem, 1)\n\n/**\n * @generated from service filesystem.Filesystem\n */\nexport const Filesystem: GenService<{\n  /**\n   * @generated from rpc filesystem.Filesystem.Stat\n   */\n  stat: {\n    methodKind: 'unary'\n    input: typeof StatRequestSchema\n    output: typeof StatResponseSchema\n  }\n  /**\n   * @generated from rpc filesystem.Filesystem.MakeDir\n   */\n  makeDir: {\n    methodKind: 'unary'\n    input: typeof MakeDirRequestSchema\n    output: typeof MakeDirResponseSchema\n  }\n  /**\n   * @generated from rpc filesystem.Filesystem.Move\n   */\n  move: {\n    methodKind: 'unary'\n    input: typeof MoveRequestSchema\n    output: typeof MoveResponseSchema\n  }\n  /**\n   * @generated from rpc filesystem.Filesystem.ListDir\n   */\n  listDir: {\n    methodKind: 'unary'\n    input: typeof ListDirRequestSchema\n    output: typeof ListDirResponseSchema\n  }\n  /**\n   * @generated from rpc filesystem.Filesystem.Remove\n   */\n  remove: {\n    methodKind: 'unary'\n    input: typeof RemoveRequestSchema\n    output: typeof RemoveResponseSchema\n  }\n  /**\n   * @generated from rpc filesystem.Filesystem.WatchDir\n   */\n  watchDir: {\n    methodKind: 'server_streaming'\n    input: typeof WatchDirRequestSchema\n    output: typeof WatchDirResponseSchema\n  }\n  /**\n   * Non-streaming versions of WatchDir\n   *\n   * @generated from rpc filesystem.Filesystem.CreateWatcher\n   */\n  createWatcher: {\n    methodKind: 'unary'\n    input: typeof CreateWatcherRequestSchema\n    output: typeof CreateWatcherResponseSchema\n  }\n  /**\n   * @generated from rpc filesystem.Filesystem.GetWatcherEvents\n   */\n  getWatcherEvents: {\n    methodKind: 'unary'\n    input: typeof GetWatcherEventsRequestSchema\n    output: typeof GetWatcherEventsResponseSchema\n  }\n  /**\n   * @generated from rpc filesystem.Filesystem.RemoveWatcher\n   */\n  removeWatcher: {\n    methodKind: 'unary'\n    input: typeof RemoveWatcherRequestSchema\n    output: typeof RemoveWatcherResponseSchema\n  }\n}> = /*@__PURE__*/ serviceDesc(file_filesystem_filesystem, 0)\n","import { handleRpcError } from '../../envd/rpc'\nimport {\n  EventType,\n  WatchDirResponse,\n} from '../../envd/filesystem/filesystem_pb'\n\n/**\n * Sandbox filesystem event types.\n */\nexport enum FilesystemEventType {\n  /**\n   * Filesystem object permissions were changed.\n   */\n  CHMOD = 'chmod',\n  /**\n   * Filesystem object was created.\n   */\n  CREATE = 'create',\n  /**\n   * Filesystem object was removed.\n   */\n  REMOVE = 'remove',\n  /**\n   * Filesystem object was renamed.\n   */\n  RENAME = 'rename',\n  /**\n   * Filesystem object was written to.\n   */\n  WRITE = 'write',\n}\n\nfunction mapEventType(type: EventType) {\n  switch (type) {\n    case EventType.CHMOD:\n      return FilesystemEventType.CHMOD\n    case EventType.CREATE:\n      return FilesystemEventType.CREATE\n    case EventType.REMOVE:\n      return FilesystemEventType.REMOVE\n    case EventType.RENAME:\n      return FilesystemEventType.RENAME\n    case EventType.WRITE:\n      return FilesystemEventType.WRITE\n  }\n}\n\n/**\n * Information about a filesystem event.\n */\nexport interface FilesystemEvent {\n  /**\n   * Relative path to the filesystem object.\n   */\n  name: string\n  /**\n   * Filesystem operation event type.\n   */\n  type: FilesystemEventType\n}\n\n/**\n * Handle for watching a directory in the sandbox filesystem.\n *\n * Use {@link WatchHandle.stop} to stop watching the directory.\n */\nexport class WatchHandle {\n  constructor(\n    private readonly handleStop: () => void,\n    private readonly events: AsyncIterable<WatchDirResponse>,\n    private readonly onEvent?: (event: FilesystemEvent) => void | Promise<void>,\n    private readonly onExit?: (err?: Error) => void | Promise<void>\n  ) {\n    this.handleEvents()\n  }\n\n  /**\n   * Stop watching the directory.\n   */\n  async stop() {\n    this.handleStop()\n  }\n\n  private async *iterateEvents() {\n    try {\n      for await (const event of this.events) {\n        switch (event.event.case) {\n          case 'filesystem':\n            yield event.event\n            break\n        }\n      }\n    } catch (err) {\n      throw handleRpcError(err)\n    }\n  }\n\n  private async handleEvents() {\n    try {\n      for await (const event of this.iterateEvents()) {\n        const eventType = mapEventType(event.value.type)\n        if (eventType === undefined) {\n          continue\n        }\n\n        this.onEvent?.({\n          name: event.value.name,\n          type: eventType,\n        })\n      }\n      this.onExit?.()\n    } catch (err) {\n      this.onExit?.(err as Error)\n    } finally {\n      this.handleStop()\n    }\n  }\n}\n","import { handleRpcError } from '../../envd/rpc'\nimport { SandboxError } from '../../errors'\nimport { ConnectResponse, StartResponse } from '../../envd/process/process_pb'\n\ndeclare const __brand: unique symbol\ntype Brand<B> = { [__brand]: B }\nexport type Branded<T, B> = T & Brand<B>\n\nexport type Stdout = Branded<string, 'stdout'>\nexport type Stderr = Branded<string, 'stderr'>\nexport type PtyOutput = Branded<Uint8Array, 'pty'>\n\n/**\n * Command execution result.\n */\nexport interface CommandResult {\n  /**\n   * Command execution exit code.\n   * `0` if the command finished successfully.\n   */\n  exitCode: number\n  /**\n   * Error message from command execution if it failed.\n   */\n  error?: string\n  /**\n   * Command stdout output.\n   */\n  stdout: string\n  /**\n   * Command stderr output.\n   */\n  stderr: string\n}\n\n/**\n * Error thrown when a command exits with a non-zero exit code.\n */\nexport class CommandExitError extends SandboxError implements CommandResult {\n  constructor(private readonly result: CommandResult) {\n    super(result.error)\n    this.name = 'CommandExitError'\n  }\n\n  /**\n   * Command execution exit code.\n   * `0` if the command finished successfully.\n   */\n  get exitCode() {\n    return this.result.exitCode\n  }\n\n  /**\n   * Error message from command execution.\n   */\n  get error() {\n    return this.result.error\n  }\n\n  /**\n   * Command execution stdout output.\n   */\n  get stdout() {\n    return this.result.stdout\n  }\n\n  /**\n   * Command execution stderr output.\n   */\n  get stderr() {\n    return this.result.stderr\n  }\n}\n\n/**\n * Command execution handle.\n *\n * It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command.\n *\n * @property {number} pid process ID of the command.\n */\nexport class CommandHandle\n  implements\n    Omit<CommandResult, 'exitCode' | 'error'>,\n    Partial<Pick<CommandResult, 'exitCode' | 'error'>>\n{\n  private _stdout = ''\n  private _stderr = ''\n\n  private result?: CommandResult\n  private iterationError?: Error\n\n  private readonly _wait: Promise<void>\n\n  /**\n   * @hidden\n   * @internal\n   * @access protected\n   */\n  constructor(\n    readonly pid: number,\n    private readonly handleDisconnect: () => void,\n    private readonly handleKill: () => Promise<boolean>,\n    private readonly events: AsyncIterable<ConnectResponse | StartResponse>,\n    private readonly onStdout?: (stdout: string) => void | Promise<void>,\n    private readonly onStderr?: (stderr: string) => void | Promise<void>,\n    private readonly onPty?: (pty: Uint8Array) => void | Promise<void>\n  ) {\n    this._wait = this.handleEvents()\n  }\n\n  /**\n   * Command execution exit code.\n   * `0` if the command finished successfully.\n   *\n   * It is `undefined` if the command is still running.\n   */\n  get exitCode() {\n    return this.result?.exitCode\n  }\n\n  /**\n   * Error message from command execution.\n   */\n  get error() {\n    return this.result?.error\n  }\n\n  /**\n   * Command execution stderr output.\n   */\n  get stderr() {\n    return this._stderr\n  }\n\n  /**\n   * Command execution stdout output.\n   */\n  get stdout() {\n    return this._stdout\n  }\n\n  /**\n   * Wait for the command to finish and return the result.\n   * If the command exits with a non-zero exit code, it throws a `CommandExitError`.\n   *\n   * @returns `CommandResult` result of command execution.\n   */\n  async wait() {\n    await this._wait\n\n    if (this.iterationError) {\n      throw this.iterationError\n    }\n\n    if (!this.result) {\n      throw new SandboxError('Process exited without a result')\n    }\n\n    if (this.result.exitCode !== 0) {\n      throw new CommandExitError(this.result)\n    }\n\n    return this.result\n  }\n\n  /**\n   * Disconnect from the command.\n   *\n   * The command is not killed, but SDK stops receiving events from the command.\n   * You can reconnect to the command using {@link Commands.connect}.\n   */\n  async disconnect() {\n    this.handleDisconnect()\n  }\n\n  /**\n   * Kill the command.\n   * It uses `SIGKILL` signal to kill the command.\n   *\n   * @returns `true` if the command was killed successfully, `false` if the command was not found.\n   */\n  async kill() {\n    return await this.handleKill()\n  }\n\n  private async *iterateEvents(): AsyncGenerator<\n    [Stdout, null, null] | [null, Stderr, null] | [null, null, PtyOutput]\n  > {\n    for await (const event of this.events) {\n      const e = event?.event?.event\n      let out: string | undefined\n\n      switch (e?.case) {\n        case 'data':\n          switch (e.value.output.case) {\n            case 'stdout':\n              out = new TextDecoder().decode(e.value.output.value)\n              this._stdout += out\n              yield [out as Stdout, null, null]\n              break\n            case 'stderr':\n              out = new TextDecoder().decode(e.value.output.value)\n              this._stderr += out\n              yield [null, out as Stderr, null]\n              break\n            case 'pty':\n              yield [null, null, e.value.output.value as PtyOutput]\n              break\n          }\n          break\n        case 'end':\n          this.result = {\n            exitCode: e.value.exitCode,\n            error: e.value.error,\n            stdout: this.stdout,\n            stderr: this.stderr,\n          }\n          break\n      }\n      // TODO: Handle empty events like in python SDK\n    }\n  }\n\n  private async handleEvents() {\n    try {\n      for await (const [stdout, stderr, pty] of this.iterateEvents()) {\n        if (stdout !== null) {\n          this.onStdout?.(stdout)\n        } else if (stderr !== null) {\n          this.onStderr?.(stderr)\n        } else if (pty) {\n          this.onPty?.(pty)\n        }\n      }\n    } catch (e) {\n      this.iterationError = handleRpcError(e)\n    } finally {\n      this.handleDisconnect()\n    }\n  }\n}\n","/**\n * CIDR range that represents all traffic.\n */\nexport const ALL_TRAFFIC = '0.0.0.0/0'\n","import { InvalidArgumentError } from '../../errors'\nimport { CommandExitError } from '../commands/commandHandle'\n\n/**\n * Parsed git status entry for a file.\n */\nexport interface GitFileStatus {\n  /**\n   * Path relative to the repository root.\n   */\n  name: string\n  /**\n   * Normalized status string (for example, `\"modified\"` or `\"added\"`).\n   */\n  status: GitStatusLabel\n  /**\n   * Index status character from porcelain output.\n   */\n  indexStatus: string\n  /**\n   * Working tree status character from porcelain output.\n   */\n  workingTreeStatus: string\n  /**\n   * Whether the change is staged.\n   */\n  staged: boolean\n  /**\n   * Original path when the file was renamed.\n   */\n  renamedFrom?: string\n}\n\n/**\n * Supported normalized git status labels.\n */\nexport type GitStatusLabel =\n  | 'conflict'\n  | 'renamed'\n  | 'copied'\n  | 'deleted'\n  | 'added'\n  | 'modified'\n  | 'typechange'\n  | 'untracked'\n  | 'unknown'\n\n/**\n * Scope for git config operations.\n */\nexport type GitConfigScope = 'global' | 'local' | 'system'\n\n/**\n * Parsed git repository status.\n */\nexport interface GitStatus {\n  /**\n   * Current branch name, if available.\n   */\n  currentBranch?: string\n  /**\n   * Upstream branch name, if available.\n   */\n  upstream?: string\n  /**\n   * Number of commits the branch is ahead of upstream.\n   */\n  ahead: number\n  /**\n   * Number of commits the branch is behind upstream.\n   */\n  behind: number\n  /**\n   * Whether HEAD is detached.\n   */\n  detached: boolean\n  /**\n   * List of file status entries.\n   */\n  fileStatus: GitFileStatus[]\n  /**\n   * Whether the repository has no tracked or untracked file changes.\n   */\n  isClean: boolean\n  /**\n   * Whether the repository has any tracked or untracked file changes.\n   */\n  hasChanges: boolean\n  /**\n   * Whether there are staged changes.\n   */\n  hasStaged: boolean\n  /**\n   * Whether there are untracked files.\n   */\n  hasUntracked: boolean\n  /**\n   * Whether there are merge conflicts.\n   */\n  hasConflicts: boolean\n  /**\n   * Total number of changed files.\n   */\n  totalCount: number\n  /**\n   * Number of files with staged changes.\n   */\n  stagedCount: number\n  /**\n   * Number of files with unstaged changes.\n   */\n  unstagedCount: number\n  /**\n   * Number of untracked files.\n   */\n  untrackedCount: number\n  /**\n   * Number of files with merge conflicts.\n   */\n  conflictCount: number\n}\n\n/**\n * Parsed git branch list.\n */\nexport interface GitBranches {\n  /**\n   * List of branch names.\n   */\n  branches: string[]\n  /**\n   * Current branch name, if available.\n   */\n  currentBranch?: string\n}\n\n/**\n * Escape a string for safe use in a shell command.\n *\n * This uses single-quoted shell escaping and safely handles embedded single quotes.\n */\nexport function shellEscape(value: string): string {\n  return `'${value.replace(/'/g, \"'\\\"'\\\"'\")}'`\n}\n\n/**\n * Add HTTP(S) credentials to a Git URL.\n *\n * @param url Git repository URL.\n * @param username Username for HTTP(S) authentication.\n * @param password Password or token for HTTP(S) authentication.\n * @returns URL with embedded credentials.\n */\nexport function withCredentials(\n  url: string,\n  username?: string,\n  password?: string\n): string {\n  if (!username && !password) {\n    return url\n  }\n\n  if (!username || !password) {\n    throw new InvalidArgumentError(\n      'Both username and password are required when using Git credentials.'\n    )\n  }\n\n  let parsed: URL\n  try {\n    parsed = new URL(url)\n  } catch {\n    throw new InvalidArgumentError(`Invalid Git URL: ${url}`)\n  }\n\n  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n    throw new InvalidArgumentError(\n      'Only http(s) Git URLs support username/password credentials.'\n    )\n  }\n\n  parsed.username = username\n  parsed.password = password\n\n  return parsed.toString()\n}\n\n/**\n * Strip HTTP(S) credentials from a Git URL.\n *\n * @param url Git repository URL.\n * @returns URL without embedded credentials.\n */\nexport function stripCredentials(url: string): string {\n  let parsed: URL\n  try {\n    parsed = new URL(url)\n  } catch {\n    return url\n  }\n\n  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n    return url\n  }\n\n  if (!parsed.username && !parsed.password) {\n    return url\n  }\n\n  parsed.username = ''\n  parsed.password = ''\n  return parsed.toString()\n}\n\n/**\n * Derive the default repository directory name from a Git URL.\n *\n * @param url Git repository URL.\n * @returns Repository directory name, if it can be determined.\n */\nexport function deriveRepoDirFromUrl(url: string): string | undefined {\n  let parsed: URL\n  try {\n    parsed = new URL(url)\n  } catch {\n    return undefined\n  }\n\n  const trimmedPath = parsed.pathname.replace(/\\/+$/, '')\n  const lastSegment = trimmedPath.split('/').pop()\n  if (!lastSegment) {\n    return undefined\n  }\n\n  return lastSegment.endsWith('.git') ? lastSegment.slice(0, -4) : lastSegment\n}\n\n/**\n * Build a shell-safe git command string.\n *\n * @param args Git command arguments.\n * @param repoPath Repository path for `git -C`, if provided.\n * @returns Shell-safe git command.\n */\nexport function buildGitCommand(args: string[], repoPath?: string): string {\n  const parts = ['git']\n  if (repoPath) {\n    parts.push('-C', repoPath)\n  }\n  parts.push(...args)\n\n  return parts.map((part) => shellEscape(part)).join(' ')\n}\n\ntype GitPushArgsOptions = {\n  remote?: string\n  branch?: string\n  setUpstream: boolean\n}\n\nexport function buildPushArgs(\n  remoteName: string | undefined,\n  opts: GitPushArgsOptions\n): string[] {\n  const { remote, branch, setUpstream } = opts\n  const args = ['push']\n  const targetRemote = remoteName ?? remote\n  if (setUpstream && targetRemote) {\n    args.push('--set-upstream')\n  }\n  if (targetRemote) {\n    args.push(targetRemote)\n  }\n  if (branch) {\n    args.push(branch)\n  }\n  return args\n}\n\nfunction parseAheadBehind(segment?: string): { ahead: number; behind: number } {\n  if (!segment) {\n    return { ahead: 0, behind: 0 }\n  }\n\n  let ahead = 0\n  let behind = 0\n\n  if (segment.includes('ahead')) {\n    try {\n      ahead = Number.parseInt(\n        segment.split('ahead')[1].split(',')[0].trim(),\n        10\n      )\n    } catch {\n      ahead = 0\n    }\n  }\n\n  if (segment.includes('behind')) {\n    try {\n      behind = Number.parseInt(\n        segment.split('behind')[1].split(',')[0].trim(),\n        10\n      )\n    } catch {\n      behind = 0\n    }\n  }\n\n  return { ahead, behind }\n}\n\nfunction normalizeBranchName(name: string): string {\n  if (name.startsWith('HEAD (detached at ')) {\n    return name.replace('HEAD (detached at ', '').replace(/\\)$/, '')\n  }\n\n  return name\n    .replace('HEAD (no branch)', 'HEAD')\n    .replace('No commits yet on ', '')\n    .replace('Initial commit on ', '')\n}\n\nfunction deriveStatus(\n  indexStatus: string,\n  workingStatus: string\n): GitStatusLabel {\n  const statuses = new Set([indexStatus, workingStatus])\n\n  if (statuses.has('U')) return 'conflict'\n  if (statuses.has('R')) return 'renamed'\n  if (statuses.has('C')) return 'copied'\n  if (statuses.has('D')) return 'deleted'\n  if (statuses.has('A')) return 'added'\n  if (statuses.has('M')) return 'modified'\n  if (statuses.has('T')) return 'typechange'\n  if (statuses.has('?')) return 'untracked'\n\n  return 'unknown'\n}\n\n/**\n * Parse `git status --porcelain=1 -b` output into a structured object.\n *\n * @param output Git status output.\n * @returns Parsed {@link GitStatus}.\n */\nexport function parseGitStatus(output: string): GitStatus {\n  const lines = output\n    .split('\\n')\n    .map((line) => line.replace(/\\r$/, ''))\n    .filter((line) => line.trim().length > 0)\n\n  let currentBranch: string | undefined\n  let upstream: string | undefined\n  let ahead = 0\n  let behind = 0\n  let detached = false\n  const fileStatus: GitFileStatus[] = []\n\n  if (lines.length === 0) {\n    return {\n      currentBranch,\n      upstream,\n      ahead,\n      behind,\n      detached,\n      fileStatus,\n      isClean: true,\n      hasChanges: false,\n      hasStaged: false,\n      hasUntracked: false,\n      hasConflicts: false,\n      totalCount: 0,\n      stagedCount: 0,\n      unstagedCount: 0,\n      untrackedCount: 0,\n      conflictCount: 0,\n    }\n  }\n\n  const branchLine = lines[0]\n  if (branchLine.startsWith('## ')) {\n    const branchInfo = branchLine.slice(3)\n    const aheadStart = branchInfo.indexOf(' [')\n    const branchPart =\n      aheadStart === -1 ? branchInfo : branchInfo.slice(0, aheadStart)\n    const aheadPart =\n      aheadStart === -1 ? undefined : branchInfo.slice(aheadStart + 2, -1)\n    const normalizedBranch = normalizeBranchName(branchPart)\n    const rawBranch = branchPart\n    const isDetached =\n      rawBranch.startsWith('HEAD (detached at ') ||\n      rawBranch.includes('detached')\n\n    if (isDetached || normalizedBranch.startsWith('HEAD')) {\n      detached = true\n    } else if (normalizedBranch.includes('...')) {\n      const [branch, upstreamBranch] = normalizedBranch.split('...')\n      currentBranch = branch || undefined\n      upstream = upstreamBranch || undefined\n    } else {\n      currentBranch = normalizedBranch || undefined\n    }\n\n    const aheadBehind = parseAheadBehind(aheadPart)\n    ahead = aheadBehind.ahead\n    behind = aheadBehind.behind\n  }\n\n  for (const line of lines.slice(1)) {\n    if (line.startsWith('?? ')) {\n      const name = line.slice(3)\n      fileStatus.push({\n        name,\n        status: 'untracked',\n        indexStatus: '?',\n        workingTreeStatus: '?',\n        staged: false,\n      })\n      continue\n    }\n\n    if (line.length < 3) {\n      continue\n    }\n\n    const indexStatus = line[0]\n    const workingTreeStatus = line[1]\n    const path = line.slice(3)\n\n    let renamedFrom: string | undefined\n    let name = path\n\n    if (path.includes(' -> ')) {\n      const parts = path.split(' -> ')\n      renamedFrom = parts[0]\n      name = parts.slice(1).join(' -> ')\n    }\n\n    fileStatus.push({\n      name,\n      status: deriveStatus(indexStatus, workingTreeStatus),\n      indexStatus,\n      workingTreeStatus,\n      staged: indexStatus !== ' ' && indexStatus !== '?',\n      ...(renamedFrom ? { renamedFrom } : {}),\n    })\n  }\n\n  const totalCount = fileStatus.length\n  const stagedCount = fileStatus.filter((item) => item.staged).length\n  const untrackedCount = fileStatus.filter(\n    (item) => item.status === 'untracked'\n  ).length\n  const conflictCount = fileStatus.filter(\n    (item) => item.status === 'conflict'\n  ).length\n  const unstagedCount = totalCount - stagedCount\n\n  return {\n    currentBranch,\n    upstream,\n    ahead,\n    behind,\n    detached,\n    fileStatus,\n    isClean: totalCount === 0,\n    hasChanges: totalCount > 0,\n    hasStaged: stagedCount > 0,\n    hasUntracked: untrackedCount > 0,\n    hasConflicts: conflictCount > 0,\n    totalCount,\n    stagedCount,\n    unstagedCount,\n    untrackedCount,\n    conflictCount,\n  }\n}\n\n/**\n * Parse `git branch --format=%(refname:short)\\t%(HEAD)` output.\n *\n * @param output Git branch output.\n * @returns Parsed {@link GitBranches}.\n */\nexport function parseGitBranches(output: string): GitBranches {\n  const branches: string[] = []\n  let currentBranch: string | undefined\n\n  const lines = output\n    .split('\\n')\n    .map((line) => line.trim())\n    .filter((line) => line.length > 0)\n\n  for (const line of lines) {\n    const parts = line.split('\\t')\n    const name = parts[0]\n    branches.push(name)\n    if (parts.length > 1 && parts[1] === '*') {\n      currentBranch = name\n    }\n  }\n\n  return { branches, currentBranch }\n}\n\nexport function isAuthFailure(err: unknown): boolean {\n  if (!(err instanceof CommandExitError)) {\n    return false\n  }\n\n  const message = `${err.stderr}\\n${err.stdout}`.toLowerCase()\n  const authSnippets = [\n    'authentication failed',\n    'terminal prompts disabled',\n    'could not read username',\n    'invalid username or password',\n    'access denied',\n    'permission denied',\n    'not authorized',\n  ]\n\n  return authSnippets.some((snippet) => message.includes(snippet))\n}\n\nexport function getScopeFlag(scope: GitConfigScope): `--${GitConfigScope}` {\n  if (scope !== 'global' && scope !== 'local' && scope !== 'system') {\n    throw new InvalidArgumentError(\n      'Git config scope must be one of: global, local, system.'\n    )\n  }\n  return `--${scope}`\n}\n\nexport function isMissingUpstream(err: unknown): boolean {\n  if (!(err instanceof CommandExitError)) {\n    return false\n  }\n\n  const message = `${err.stderr}\\n${err.stdout}`.toLowerCase()\n  const upstreamSnippets = [\n    'has no upstream branch',\n    'no upstream branch',\n    'no upstream configured',\n    'no tracking information for the current branch',\n    'no tracking information',\n    'set the remote as upstream',\n    'set the upstream branch',\n    'please specify which branch you want to merge with',\n  ]\n\n  return upstreamSnippets.some((snippet) => message.includes(snippet))\n}\n\nexport function buildAuthErrorMessage(\n  action: 'clone' | 'push' | 'pull',\n  missingPassword: boolean\n): string {\n  if (missingPassword) {\n    return `Git ${action} requires a password/token for private repositories.`\n  }\n  return `Git ${action} requires credentials for private repositories.`\n}\n\nexport function buildUpstreamErrorMessage(action: 'push' | 'pull'): string {\n  if (action === 'push') {\n    return (\n      'Git push failed because no upstream branch is configured. ' +\n      'Set upstream once with { setUpstream: true } (and optional remote/branch), ' +\n      'or pass remote and branch explicitly.'\n    )\n  }\n\n  return (\n    'Git pull failed because no upstream branch is configured. ' +\n    'Pass remote and branch explicitly, or set upstream once (push with { setUpstream: true } ' +\n    'or run: git branch --set-upstream-to=origin/<branch> <branch>).'\n  )\n}\n\nexport function getRepoPathForScope(\n  scope: GitConfigScope,\n  path?: string\n): string | undefined {\n  if (scope !== 'local') {\n    return undefined\n  }\n  if (!path) {\n    throw new InvalidArgumentError(\n      'A repository path is required when using scope \"local\".'\n    )\n  }\n  return path\n}\n","import {\n  GitAuthError,\n  GitUpstreamError,\n  InvalidArgumentError,\n} from '../../errors'\nimport type { CommandStartOpts } from '../commands'\nimport type { CommandResult } from '../commands/commandHandle'\nimport { Commands } from '../commands'\nimport {\n  buildAuthErrorMessage,\n  buildGitCommand,\n  buildPushArgs,\n  buildUpstreamErrorMessage,\n  GitBranches,\n  GitConfigScope,\n  GitStatus,\n  getRepoPathForScope,\n  getScopeFlag,\n  isAuthFailure,\n  isMissingUpstream,\n  parseGitBranches,\n  parseGitStatus,\n  shellEscape,\n  stripCredentials,\n  deriveRepoDirFromUrl,\n  withCredentials,\n} from './utils'\n\nconst DEFAULT_GIT_ENV: Record<string, string> = {\n  GIT_TERMINAL_PROMPT: '0',\n}\n\n/**\n * Options for git operations in the sandbox.\n */\nexport interface GitRequestOpts\n  extends Partial<\n    Pick<\n      CommandStartOpts,\n      'envs' | 'user' | 'cwd' | 'timeoutMs' | 'requestTimeoutMs'\n    >\n  > {}\n\n/**\n * Options for cloning a repository.\n */\nexport interface GitCloneOpts extends GitRequestOpts {\n  /**\n   * Destination path for the clone.\n   */\n  path?: string\n  /**\n   * Branch to check out.\n   */\n  branch?: string\n  /**\n   * If set, perform a shallow clone with this depth.\n   */\n  depth?: number\n  /**\n   * Username for HTTP(S) authentication.\n   */\n  username?: string\n  /**\n   * Password or token for HTTP(S) authentication.\n   */\n  password?: string\n  /**\n   * Store credentials in the cloned repository when `true`.\n   *\n   * @default false\n   */\n  dangerouslyStoreCredentials?: boolean\n}\n\n/**\n * Options for initializing a repository.\n */\nexport interface GitInitOpts extends GitRequestOpts {\n  /**\n   * Create a bare repository when `true`.\n   */\n  bare?: boolean\n  /**\n   * Initial branch name (for example, `\"main\"`).\n   */\n  initialBranch?: string\n}\n\n/**\n * Options for adding a git remote.\n */\nexport interface GitRemoteAddOpts extends GitRequestOpts {\n  /**\n   * Fetch the remote after adding it when `true`.\n   */\n  fetch?: boolean\n  /**\n   * Overwrite the remote URL if the remote already exists when `true`.\n   */\n  overwrite?: boolean\n}\n\n/**\n * Options for creating a commit.\n */\nexport interface GitCommitOpts extends GitRequestOpts {\n  /**\n   * Commit author name.\n   */\n  authorName?: string\n  /**\n   * Commit author email.\n   */\n  authorEmail?: string\n  /**\n   * Allow empty commits when `true`.\n   */\n  allowEmpty?: boolean\n}\n\n/**\n * Options for staging files.\n */\nexport interface GitAddOpts extends GitRequestOpts {\n  /**\n   * Files to add; when omitted, adds the current directory.\n   */\n  files?: string[]\n  /**\n   * When `true` and `files` is omitted, stage all changes.\n   */\n  all?: boolean\n}\n\n/**\n * Supported reset modes.\n */\nexport type GitResetMode = 'soft' | 'mixed' | 'hard' | 'merge' | 'keep'\n\n/**\n * Options for resetting a repository.\n */\nexport interface GitResetOpts extends GitRequestOpts {\n  /**\n   * Reset mode to use.\n   */\n  mode?: GitResetMode\n  /**\n   * Commit, branch, or ref to reset to (defaults to HEAD).\n   */\n  target?: string\n  /**\n   * Paths to reset.\n   */\n  paths?: string[]\n}\n\n/**\n * Options for restoring files or unstaging changes.\n */\nexport interface GitRestoreOpts extends GitRequestOpts {\n  /**\n   * Paths to restore (use `['.']` for all).\n   */\n  paths: string[]\n  /**\n   * Restore the index (unstage).\n   */\n  staged?: boolean\n  /**\n   * Restore working tree files.\n   */\n  worktree?: boolean\n  /**\n   * Restore from the given source (commit, branch, or ref).\n   */\n  source?: string\n}\n/**\n * Options for deleting a branch.\n */\nexport interface GitDeleteBranchOpts extends GitRequestOpts {\n  /**\n   * Force deletion with `-D` when `true`.\n   */\n  force?: boolean\n}\n\n/**\n * Options for pushing commits.\n */\nexport interface GitPushOpts extends GitRequestOpts {\n  /**\n   * Remote name (for example, `\"origin\"`).\n   */\n  remote?: string\n  /**\n   * Branch name to push.\n   */\n  branch?: string\n  /**\n   * Set upstream tracking when `true`.\n   */\n  setUpstream?: boolean\n  /**\n   * Username for HTTP(S) authentication.\n   */\n  username?: string\n  /**\n   * Password or token for HTTP(S) authentication.\n   */\n  password?: string\n}\n\n/**\n * Options for pulling commits.\n */\nexport interface GitPullOpts extends GitRequestOpts {\n  /**\n   * Remote name (for example, `\"origin\"`).\n   */\n  remote?: string\n  /**\n   * Branch name to pull.\n   */\n  branch?: string\n  /**\n   * Username for HTTP(S) authentication.\n   */\n  username?: string\n  /**\n   * Password or token for HTTP(S) authentication.\n   */\n  password?: string\n}\n\n/**\n * Supported scopes for git config operations.\n */\n/**\n * Options for git config operations.\n */\nexport interface GitConfigOpts extends GitRequestOpts {\n  /**\n   * Scope for the git config command.\n   *\n   * @default \"global\"\n   */\n  scope?: GitConfigScope\n  /**\n   * Repository path required when `scope` is `\"local\"`.\n   */\n  path?: string\n}\n\n/**\n * Options for dangerously authenticating git globally via the credential helper.\n */\nexport interface GitDangerouslyAuthenticateOpts extends GitRequestOpts {\n  /**\n   * Username for HTTP(S) authentication.\n   */\n  username: string\n  /**\n   * Password or token for HTTP(S) authentication.\n   */\n  password: string\n  /**\n   * Host to authenticate for.\n   *\n   * @default \"github.com\"\n   */\n  host?: string\n  /**\n   * Protocol to authenticate for.\n   *\n   * @default \"https\"\n   */\n  protocol?: string\n}\n\n/**\n * Module for running git operations in the sandbox.\n */\nexport class Git {\n  constructor(private readonly commands: Commands) {}\n\n  /**\n   * Clone a git repository into the sandbox.\n   *\n   * @param url Git repository URL.\n   * @param opts Clone options.\n   * @returns Command result from the command runner.\n   */\n  async clone(url: string, opts?: GitCloneOpts): Promise<CommandResult> {\n    const {\n      username,\n      password,\n      branch,\n      depth,\n      path,\n      dangerouslyStoreCredentials,\n      ...rest\n    } = opts ?? {}\n\n    if (password && !username) {\n      throw new InvalidArgumentError(\n        'Username is required when using a password or token for git clone.'\n      )\n    }\n\n    const attemptClone = async (\n      authUsername?: string,\n      authPassword?: string\n    ): Promise<CommandResult> => {\n      const urlWithCreds =\n        authUsername && authPassword\n          ? withCredentials(url, authUsername, authPassword)\n          : url\n\n      const sanitizedUrl = stripCredentials(urlWithCreds)\n      const stripInlineCreds =\n        !dangerouslyStoreCredentials && sanitizedUrl !== urlWithCreds\n\n      const repoPath = stripInlineCreds\n        ? (path ?? deriveRepoDirFromUrl(url))\n        : path\n\n      if (stripInlineCreds && !repoPath) {\n        throw new InvalidArgumentError(\n          'A destination path is required when using credentials without storing them.'\n        )\n      }\n\n      const args = ['clone', urlWithCreds]\n\n      if (branch) args.push('--branch', branch, '--single-branch')\n      if (depth) args.push('--depth', depth.toString())\n      if (repoPath) args.push(repoPath)\n\n      const result = await this.runGit(args, undefined, rest)\n\n      if (stripInlineCreds) {\n        await this.runGit(\n          ['remote', 'set-url', 'origin', sanitizedUrl],\n          repoPath,\n          rest\n        )\n      }\n\n      return result\n    }\n\n    try {\n      return await attemptClone(username, password)\n    } catch (err) {\n      if (isAuthFailure(err)) {\n        throw new GitAuthError(\n          buildAuthErrorMessage('clone', Boolean(username) && !password)\n        )\n      }\n      throw err\n    }\n  }\n\n  /**\n   * Initialize a new git repository.\n   *\n   * @param path Destination path for the repository.\n   * @param opts Init options.\n   * @returns Command result from the command runner.\n   */\n  async init(path: string, opts?: GitInitOpts): Promise<CommandResult> {\n    const { bare, initialBranch, ...rest } = opts ?? {}\n    const args = ['init']\n\n    if (initialBranch) {\n      args.push('--initial-branch', initialBranch)\n    }\n    if (bare) {\n      args.push('--bare')\n    }\n\n    args.push(path)\n    return this.runGit(args, undefined, rest)\n  }\n\n  /**\n   * Add (or update) a remote for a repository.\n   *\n   * @param path Repository path.\n   * @param name Remote name (for example, `\"origin\"`).\n   * @param url Remote URL.\n   * @param opts Remote add options.\n   * @returns Command result from the command runner.\n   */\n  async remoteAdd(\n    path: string,\n    name: string,\n    url: string,\n    opts?: GitRemoteAddOpts\n  ): Promise<CommandResult> {\n    if (!name || !url) {\n      throw new InvalidArgumentError(\n        'Both remote name and URL are required to add a git remote.'\n      )\n    }\n\n    const { fetch, overwrite, ...rest } = opts ?? {}\n    const addArgs = ['remote', 'add']\n\n    if (fetch) {\n      addArgs.push('-f')\n    }\n\n    addArgs.push(name, url)\n\n    if (!overwrite) {\n      return this.runGit(addArgs, path, rest)\n    }\n\n    const addCmd = buildGitCommand(addArgs, path)\n    const setUrlCmd = buildGitCommand(['remote', 'set-url', name, url], path)\n    let cmd = `${addCmd} || ${setUrlCmd}`\n    if (fetch) {\n      const fetchCmd = buildGitCommand(['fetch', name], path)\n      cmd = `(${cmd}) && ${fetchCmd}`\n    }\n    return this.runShell(cmd, rest)\n  }\n\n  /**\n   * Get the URL for a git remote.\n   *\n   * Returns `undefined` when the remote does not exist.\n   *\n   * @param path Repository path.\n   * @param name Remote name (for example, `\"origin\"`).\n   * @param opts Command execution options.\n   * @returns Remote URL if present.\n   */\n  async remoteGet(\n    path: string,\n    name: string,\n    opts?: GitRequestOpts\n  ): Promise<string | undefined> {\n    if (!name) {\n      throw new InvalidArgumentError('Remote name is required.')\n    }\n\n    const cmd = `${buildGitCommand(['remote', 'get-url', name], path)} || true`\n    const result = await this.runShell(cmd, opts)\n    const trimmed = result.stdout.trim()\n    return trimmed.length > 0 ? trimmed : undefined\n  }\n\n  /**\n   * Get repository status information.\n   *\n   * @param path Repository path.\n   * @param opts Command execution options.\n   * @returns Parsed git status.\n   */\n  async status(path: string, opts?: GitRequestOpts): Promise<GitStatus> {\n    const result = await this.runGit(\n      ['status', '--porcelain=1', '-b'],\n      path,\n      opts\n    )\n    return parseGitStatus(result.stdout)\n  }\n\n  /**\n   * List branches in a repository.\n   *\n   * @param path Repository path.\n   * @param opts Command execution options.\n   * @returns Parsed branch list.\n   */\n  async branches(path: string, opts?: GitRequestOpts): Promise<GitBranches> {\n    const result = await this.runGit(\n      ['branch', '--format=%(refname:short)\\t%(HEAD)'],\n      path,\n      opts\n    )\n    return parseGitBranches(result.stdout)\n  }\n\n  /**\n   * Create and check out a new branch.\n   *\n   * @param path Repository path.\n   * @param branch Branch name to create.\n   * @param opts Command execution options.\n   * @returns Command result from the command runner.\n   */\n  async createBranch(\n    path: string,\n    branch: string,\n    opts?: GitRequestOpts\n  ): Promise<CommandResult> {\n    return this.runGit(['checkout', '-b', branch], path, opts)\n  }\n\n  /**\n   * Check out an existing branch.\n   *\n   * @param path Repository path.\n   * @param branch Branch name to check out.\n   * @param opts Command execution options.\n   * @returns Command result from the command runner.\n   */\n  async checkoutBranch(\n    path: string,\n    branch: string,\n    opts?: GitRequestOpts\n  ): Promise<CommandResult> {\n    return this.runGit(['checkout', branch], path, opts)\n  }\n\n  /**\n   * Delete a branch.\n   *\n   * @param path Repository path.\n   * @param branch Branch name to delete.\n   * @param opts Delete options.\n   * @returns Command result from the command runner.\n   */\n  async deleteBranch(\n    path: string,\n    branch: string,\n    opts?: GitDeleteBranchOpts\n  ): Promise<CommandResult> {\n    const { force, ...rest } = opts ?? {}\n    const args = ['branch', force ? '-D' : '-d', branch]\n    return this.runGit(args, path, rest)\n  }\n\n  /**\n   * Stage files for commit.\n   *\n   * @param path Repository path.\n   * @param opts Add options.\n   * @returns Command result from the command runner.\n   */\n  async add(path: string, opts?: GitAddOpts): Promise<CommandResult> {\n    const { files, all = true, ...rest } = opts ?? {}\n    const args = ['add']\n\n    if (!files || files.length === 0) {\n      args.push(all ? '-A' : '.')\n    } else {\n      args.push('--', ...files)\n    }\n\n    return this.runGit(args, path, rest)\n  }\n\n  /**\n   * Create a commit in the repository.\n   *\n   * @param path Repository path.\n   * @param message Commit message.\n   * @param opts Commit options.\n   * @returns Command result from the command runner.\n   */\n  async commit(\n    path: string,\n    message: string,\n    opts?: GitCommitOpts\n  ): Promise<CommandResult> {\n    const { authorName, authorEmail, allowEmpty, ...rest } = opts ?? {}\n    const args = ['commit', '-m', message]\n\n    if (allowEmpty) {\n      args.push('--allow-empty')\n    }\n\n    const authorArgs: string[] = []\n    if (authorName) {\n      authorArgs.push('-c', `user.name=${authorName}`)\n    }\n    if (authorEmail) {\n      authorArgs.push('-c', `user.email=${authorEmail}`)\n    }\n\n    return this.runGit([...authorArgs, ...args], path, rest)\n  }\n\n  /**\n   * Reset the current HEAD to a specified state.\n   *\n   * @param path Repository path.\n   * @param opts Reset options.\n   * @returns Command result from the command runner.\n   */\n  async reset(path: string, opts?: GitResetOpts): Promise<CommandResult> {\n    const { mode, target, paths, ...rest } = opts ?? {}\n    const allowedModes: GitResetMode[] = [\n      'soft',\n      'mixed',\n      'hard',\n      'merge',\n      'keep',\n    ]\n\n    if (mode && !allowedModes.includes(mode)) {\n      throw new InvalidArgumentError(\n        `Reset mode must be one of ${allowedModes.join(', ')}.`\n      )\n    }\n\n    const args = ['reset']\n    if (mode) {\n      args.push(`--${mode}`)\n    }\n    if (target) {\n      args.push(target)\n    }\n    if (paths && paths.length > 0) {\n      args.push('--', ...paths)\n    }\n\n    return this.runGit(args, path, rest)\n  }\n\n  /**\n   * Restore working tree files or unstage changes.\n   *\n   * @param path Repository path.\n   * @param opts Restore options.\n   * @returns Command result from the command runner.\n   */\n  async restore(path: string, opts: GitRestoreOpts): Promise<CommandResult> {\n    const { paths, staged, worktree, source, ...rest } = opts\n\n    if (!paths || paths.length === 0) {\n      throw new InvalidArgumentError('At least one path is required.')\n    }\n\n    let resolvedStaged = staged\n    let resolvedWorktree = worktree\n\n    if (staged === undefined && worktree === undefined) {\n      resolvedWorktree = true\n    } else if (staged === true && worktree === undefined) {\n      resolvedWorktree = false\n    } else if (staged === undefined && worktree !== undefined) {\n      resolvedStaged = false\n    }\n\n    if (resolvedStaged === false && resolvedWorktree === false) {\n      throw new InvalidArgumentError(\n        'At least one of staged or worktree must be true.'\n      )\n    }\n\n    const args = ['restore']\n    if (resolvedWorktree) {\n      args.push('--worktree')\n    }\n    if (resolvedStaged) {\n      args.push('--staged')\n    }\n    if (source) {\n      args.push('--source', source)\n    }\n    args.push('--', ...paths)\n\n    return this.runGit(args, path, rest)\n  }\n\n  /**\n   * Push commits to a remote.\n   *\n   * @param path Repository path.\n   * @param opts Push options.\n   * @returns Command result from the command runner.\n   */\n  async push(path: string, opts?: GitPushOpts): Promise<CommandResult> {\n    const {\n      remote,\n      branch,\n      setUpstream = true,\n      username,\n      password,\n      ...rest\n    } = opts ?? {}\n\n    if (password && !username) {\n      throw new InvalidArgumentError(\n        'Username is required when using a password or token for git push.'\n      )\n    }\n\n    if (username && password) {\n      const remoteName = await this.resolveRemoteName(path, remote, rest)\n      return this.withRemoteCredentials(\n        path,\n        remoteName,\n        username,\n        password,\n        rest,\n        () =>\n          this.runGit(\n            buildPushArgs(remoteName, { remote, branch, setUpstream }),\n            path,\n            rest\n          )\n      )\n    }\n\n    try {\n      return await this.runGit(\n        buildPushArgs(undefined, { remote, branch, setUpstream }),\n        path,\n        rest\n      )\n    } catch (err) {\n      if (isAuthFailure(err)) {\n        throw new GitAuthError(\n          buildAuthErrorMessage('push', Boolean(username) && !password)\n        )\n      }\n      if (isMissingUpstream(err)) {\n        throw new GitUpstreamError(buildUpstreamErrorMessage('push'))\n      }\n      throw err\n    }\n  }\n\n  /**\n   * Pull changes from a remote.\n   *\n   * @param path Repository path.\n   * @param opts Pull options.\n   * @returns Command result from the command runner.\n   */\n  async pull(path: string, opts?: GitPullOpts): Promise<CommandResult> {\n    const { remote, branch, username, password, ...rest } = opts ?? {}\n    if (password && !username) {\n      throw new InvalidArgumentError(\n        'Username is required when using a password or token for git pull.'\n      )\n    }\n\n    if (!remote && !branch) {\n      const hasUpstream = await this.hasUpstream(path, rest)\n      if (!hasUpstream) {\n        throw new GitUpstreamError(buildUpstreamErrorMessage('pull'))\n      }\n    }\n\n    const buildArgs = (remoteName?: string) => {\n      const args = ['pull']\n      const targetRemote = remoteName ?? remote\n      if (targetRemote) {\n        args.push(targetRemote)\n      }\n      if (branch) {\n        args.push(branch)\n      }\n      return args\n    }\n\n    if (username && password) {\n      const remoteName = await this.resolveRemoteName(path, remote, rest)\n      return this.withRemoteCredentials(\n        path,\n        remoteName,\n        username,\n        password,\n        rest,\n        () => this.runGit(buildArgs(remoteName), path, rest)\n      )\n    }\n\n    try {\n      return await this.runGit(buildArgs(), path, rest)\n    } catch (err) {\n      if (isAuthFailure(err)) {\n        throw new GitAuthError(\n          buildAuthErrorMessage('pull', Boolean(username) && !password)\n        )\n      }\n      if (isMissingUpstream(err)) {\n        throw new GitUpstreamError(buildUpstreamErrorMessage('pull'))\n      }\n      throw err\n    }\n  }\n\n  /**\n   * Set a git config value.\n   *\n   * Use `scope: \"local\"` together with `path` to configure a specific repository.\n   *\n   * @param key Git config key (for example, `\"pull.rebase\"`).\n   * @param value Git config value.\n   * @param opts Config options.\n   * @returns Command result from the command runner.\n   */\n  async setConfig(\n    key: string,\n    value: string,\n    opts?: GitConfigOpts\n  ): Promise<CommandResult> {\n    if (!key) {\n      throw new InvalidArgumentError('Git config key is required.')\n    }\n\n    const scope = opts?.scope ?? 'global'\n    const scopeFlag = getScopeFlag(scope)\n    const repoPath = getRepoPathForScope(scope, opts?.path)\n\n    return this.runGit(['config', scopeFlag, key, value], repoPath, opts)\n  }\n\n  /**\n   * Get a git config value.\n   *\n   * Returns `undefined` when the key is not set in the requested scope.\n   *\n   * @param key Git config key (for example, `\"pull.rebase\"`).\n   * @param opts Config options.\n   * @returns The config value if present.\n   */\n  async getConfig(\n    key: string,\n    opts?: GitConfigOpts\n  ): Promise<string | undefined> {\n    if (!key) {\n      throw new InvalidArgumentError('Git config key is required.')\n    }\n\n    const scope = opts?.scope ?? 'global'\n    const scopeFlag = getScopeFlag(scope)\n    const repoPath = getRepoPathForScope(scope, opts?.path)\n    const cmd = `${buildGitCommand(['config', scopeFlag, '--get', key], repoPath)} || true`\n    const result = await this.runShell(cmd, opts)\n    const trimmed = result.stdout.trim()\n    return trimmed.length > 0 ? trimmed : undefined\n  }\n\n  /**\n   * Dangerously authenticate git globally via the credential helper.\n   *\n   * This persists credentials in the credential store.\n   * Prefer short-lived credentials when possible.\n   *\n   * @param opts Authentication options.\n   * @returns Command result from the command runner.\n   */\n  async dangerouslyAuthenticate(\n    opts: GitDangerouslyAuthenticateOpts\n  ): Promise<CommandResult> {\n    const { username, password, host, protocol, ...rest } = opts\n\n    if (!username || !password) {\n      throw new InvalidArgumentError(\n        'Both username and password are required to authenticate git.'\n      )\n    }\n\n    const targetHost = (host ?? 'github.com').trim()\n    const targetProtocol = (protocol ?? 'https').trim()\n    const credentialInput = [\n      `protocol=${targetProtocol}`,\n      `host=${targetHost}`,\n      `username=${username}`,\n      `password=${password}`,\n      '',\n      '',\n    ].join('\\n')\n\n    await this.runGit(\n      ['config', '--global', 'credential.helper', 'store'],\n      undefined,\n      rest\n    )\n\n    const approveCmd = `printf %s ${shellEscape(credentialInput)} | ${buildGitCommand(\n      ['credential', 'approve']\n    )}`\n\n    return this.runShell(approveCmd, rest)\n  }\n\n  /**\n   * Configure git user name and email.\n   *\n   * @param name Git user name.\n   * @param email Git user email.\n   * @param opts Config options.\n   * @returns Command result from the command runner.\n   */\n  async configureUser(\n    name: string,\n    email: string,\n    opts?: GitConfigOpts\n  ): Promise<CommandResult> {\n    if (!name || !email) {\n      throw new InvalidArgumentError('Both name and email are required.')\n    }\n\n    const scope = opts?.scope ?? 'global'\n    const configOpts = { ...opts, scope }\n\n    await this.setConfig('user.name', name, configOpts)\n    return this.setConfig('user.email', email, configOpts)\n  }\n\n  /**\n   * Build and execute a git command inside the sandbox.\n   *\n   * @param args Git arguments to pass to the git binary.\n   * @param repoPath Repository path used with `git -C`, if provided.\n   * @param opts Command execution options.\n   * @returns Command result from the command runner.\n   */\n  private async runGit(\n    args: string[],\n    repoPath?: string,\n    opts?: GitRequestOpts\n  ): Promise<CommandResult> {\n    const { envs, ...rest } = opts ?? {}\n    const cmd = buildGitCommand(args, repoPath)\n    const mergedEnvs = { ...DEFAULT_GIT_ENV, ...(envs ?? {}) }\n\n    return this.commands.run(cmd, {\n      ...rest,\n      envs: mergedEnvs,\n    })\n  }\n\n  /**\n   * Execute a raw shell command while applying default git environment variables.\n   * \n   Note: We can likely just modify runGit later to allow appending commands to the git but for now it's separate.\n   */\n  private async runShell(\n    cmd: string,\n    opts?: GitRequestOpts\n  ): Promise<CommandResult> {\n    const { envs, ...rest } = opts ?? {}\n    const mergedEnvs = { ...DEFAULT_GIT_ENV, ...(envs ?? {}) }\n\n    return this.commands.run(cmd, {\n      ...rest,\n      envs: mergedEnvs,\n    })\n  }\n\n  private async getRemoteUrl(\n    path: string,\n    remote: string,\n    opts?: GitRequestOpts\n  ): Promise<string> {\n    const result = await this.runGit(['remote', 'get-url', remote], path, opts)\n    const url = result.stdout.trim()\n    if (!url) {\n      throw new InvalidArgumentError(\n        `Remote \"${remote}\" URL not found in repository.`\n      )\n    }\n    return url\n  }\n\n  private async resolveRemoteName(\n    path: string,\n    remote: string | undefined,\n    opts?: GitRequestOpts\n  ): Promise<string> {\n    if (remote) {\n      return remote\n    }\n\n    const result = await this.runGit(['remote'], path, opts)\n    const remotes = result.stdout\n      .split('\\n')\n      .map((line) => line.trim())\n      .filter(Boolean)\n\n    if (remotes.length === 1) {\n      return remotes[0]\n    }\n\n    throw new InvalidArgumentError(\n      'Remote is required when using username/password and the repository has multiple remotes.'\n    )\n  }\n\n  private async withRemoteCredentials<T>(\n    path: string,\n    remote: string,\n    username: string,\n    password: string,\n    opts: GitRequestOpts | undefined,\n    operation: () => Promise<T>\n  ): Promise<T> {\n    const originalUrl = await this.getRemoteUrl(path, remote, opts)\n    const credentialUrl = withCredentials(originalUrl, username, password)\n\n    await this.runGit(['remote', 'set-url', remote, credentialUrl], path, opts)\n\n    let result: T | undefined\n    let operationError: unknown\n    try {\n      result = await operation()\n    } catch (err) {\n      operationError = err\n    }\n\n    let restoreError: unknown\n    try {\n      await this.runGit(['remote', 'set-url', remote, originalUrl], path, opts)\n    } catch (err) {\n      restoreError = err\n    }\n\n    if (operationError) {\n      throw operationError\n    }\n    if (restoreError) {\n      throw restoreError\n    }\n\n    return result as T\n  }\n\n  private async hasUpstream(\n    path: string,\n    opts?: GitRequestOpts\n  ): Promise<boolean> {\n    try {\n      const result = await this.runGit(\n        ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'],\n        path,\n        opts\n      )\n      return result.stdout.trim().length > 0\n    } catch {\n      return false\n    }\n  }\n}\n\nexport type {\n  GitBranches,\n  GitConfigScope,\n  GitFileStatus,\n  GitStatus,\n} from './utils'\n","import createClient from 'openapi-fetch'\n\nimport type { components, paths } from './schema.gen'\nimport { defaultHeaders, getEnvVar } from '../api/metadata'\nimport { buildRequestSignal } from '../connectionConfig'\nimport { createApiLogger, Logger } from '../logs'\nimport type { Volume } from './index'\n\nconst FILE_TIMEOUT_MS = 3_600_000 // 1 hour\n\nexport interface VolumeApiOpts {\n  /**\n   * E2B API key to use for authentication.\n   *\n   * @default E2B_API_KEY // environment variable\n   */\n  token?: string\n  /**\n   * Domain to use for the volume API.\n   *\n   * @default E2B_DOMAIN // environment variable or `e2b.app`\n   */\n  domain?: string\n  /**\n   * If true the SDK starts in the debug mode and connects to the local volume API server.\n   * @internal\n   * @default E2B_DEBUG // environment variable or `false`\n   */\n  debug?: boolean\n  /**\n   * API Url to use for the API.\n   * @internal\n   * @default E2B_VOLUME_API_URL // environment variable or `https://api.${domain}`\n   */\n  apiUrl?: string\n  /**\n   * Timeout for requests to the API in **milliseconds**.\n   *\n   * @default 60_000 // 60 seconds\n   */\n  requestTimeoutMs?: number\n  /**\n   * Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, {@link console}.\n   */\n  logger?: Logger\n\n  /**\n   * Additional headers to send with the request.\n   */\n  headers?: Record<string, string>\n\n  /**\n   * An optional `AbortSignal` that can be used to cancel the in-flight request.\n   * When the signal is aborted, the underlying `fetch` is aborted and the\n   * returned promise rejects with an `AbortError`.\n   */\n  signal?: AbortSignal\n}\n\nexport class VolumeConnectionConfig {\n  readonly domain: string\n  readonly debug: boolean\n  readonly apiUrl: string\n  readonly token?: string\n  readonly headers?: Record<string, string>\n  readonly logger?: Logger\n  readonly requestTimeoutMs?: number\n\n  constructor(volume: Volume, opts?: VolumeApiOpts) {\n    this.domain = opts?.domain || volume.domain || VolumeConnectionConfig.domain\n    this.debug = opts?.debug ?? volume.debug ?? VolumeConnectionConfig.debug\n    this.apiUrl =\n      opts?.apiUrl ||\n      VolumeConnectionConfig.volumeApiUrl ||\n      (this.debug ? 'http://localhost:8080' : `https://api.${this.domain}`)\n    this.token = opts?.token || volume.token\n    this.headers = opts?.headers\n    this.logger = opts?.logger\n    this.requestTimeoutMs = opts?.requestTimeoutMs\n  }\n\n  private static get domain() {\n    return getEnvVar('E2B_DOMAIN') || 'e2b.app'\n  }\n\n  private static get debug() {\n    return (getEnvVar('E2B_DEBUG') || 'false').toLowerCase() === 'true'\n  }\n\n  private static get volumeApiUrl() {\n    return getEnvVar('E2B_VOLUME_API_URL')\n  }\n\n  getSignal(requestTimeoutMs?: number, signal?: AbortSignal) {\n    return buildRequestSignal(requestTimeoutMs ?? this.requestTimeoutMs, signal)\n  }\n}\n\n/**\n * Client for interacting with the E2B Volume API.\n */\nclass VolumeApiClient {\n  readonly api: ReturnType<typeof createClient<paths>>\n\n  constructor(config: VolumeConnectionConfig) {\n    this.api = createClient<paths>({\n      baseUrl: config.apiUrl,\n      headers: {\n        ...defaultHeaders,\n        ...(config.token && { Authorization: `Bearer ${config.token}` }),\n        ...config.headers,\n      },\n    })\n\n    if (config.logger) {\n      this.api.use(createApiLogger(config.logger))\n    }\n  }\n}\n\nexport type { components as VolumeApiComponents, paths as VolumeApiPaths }\nexport { VolumeApiClient, FILE_TIMEOUT_MS }\n","import { VolumeApiComponents } from './client'\n\n/**\n * File type enum.\n */\nexport enum VolumeFileType {\n  UNKNOWN = 'unknown',\n  FILE = 'file',\n  DIRECTORY = 'directory',\n  SYMLINK = 'symlink',\n}\n\n/**\n * Information about a volume.\n */\nexport type VolumeInfo = {\n  /**\n   * Volume ID.\n   */\n  volumeId: string\n\n  /**\n   * Volume name.\n   */\n  name: string\n}\n\n/**\n * Information about a volume and its auth token.\n */\nexport type VolumeAndToken = VolumeInfo & {\n  /**\n   * Volume auth token.\n   */\n  token: string\n}\n\n/**\n * Volume entry stat with dates converted to Date objects.\n */\nexport type VolumeEntryStat = Omit<\n  VolumeApiComponents['schemas']['VolumeEntryStat'],\n  'atime' | 'mtime' | 'ctime' | 'type'\n> & {\n  /**\n   * Access time as a Date object.\n   */\n  atime: Date\n\n  /**\n   * Modification time as a Date object.\n   */\n  mtime: Date\n\n  /**\n   * Creation time as a Date object.\n   */\n  ctime: Date\n\n  /**\n   * File type.\n   */\n  type: VolumeFileType\n}\n\n/**\n * Options for updating file metadata.\n */\nexport type VolumeMetadataOptions = {\n  /**\n   * User ID of the file or directory.\n   */\n  uid?: number\n\n  /**\n   * Group ID of the file or directory.\n   */\n  gid?: number\n\n  /**\n   * Mode of the file or directory.\n   */\n  mode?: number\n}\n\n/**\n * Options for file and directory operations.\n */\nexport type VolumeWriteOptions = VolumeMetadataOptions & {\n  /**\n   * For makeDir: Create parent directories if they don't exist.\n   * For writeFile: Force overwrite of an existing file.\n   */\n  force?: boolean\n}\n","import { ApiClient, handleApiError, components as ApiComponents } from '../api'\nimport {\n  VolumeApiClient,\n  VolumeApiComponents,\n  VolumeConnectionConfig,\n  VolumeApiOpts,\n  FILE_TIMEOUT_MS,\n} from './client'\nimport { ConnectionConfig, ConnectionOpts } from '../connectionConfig'\nimport { NotFoundError, VolumeError } from '../errors'\nimport { toBlob } from '../utils'\nimport { VolumeFileType } from './types'\nimport type {\n  VolumeAndToken,\n  VolumeEntryStat,\n  VolumeInfo,\n  VolumeMetadataOptions,\n  VolumeWriteOptions,\n} from './types'\n\n/**\n * Convert API VolumeEntryStat to SDK VolumeEntryStat.\n */\nfunction convertVolumeEntryStat(\n  entry: VolumeApiComponents['schemas']['VolumeEntryStat']\n): VolumeEntryStat {\n  return {\n    ...entry,\n    type: entry.type as VolumeFileType,\n    atime: new Date(entry.atime),\n    mtime: new Date(entry.mtime),\n    ctime: new Date(entry.ctime),\n  }\n}\n\n/**\n * Module for interacting with E2B volumes.\n *\n * Create a `Volume` instance to interact with a volume by its ID,\n * or use the static methods to manage volumes.\n */\nexport class Volume {\n  /**\n   * Volume ID.\n   */\n  readonly volumeId: string\n\n  /**\n   * Volume name.\n   */\n  readonly name: string\n\n  /**\n   * Volume auth token.\n   */\n  readonly token: string\n\n  /**\n   * Domain used for constructing the volume API URL.\n   */\n  readonly domain?: string\n\n  /**\n   * Whether to use debug mode (connects to local volume API server).\n   */\n  readonly debug?: boolean\n\n  /**\n   * Create a local Volume instance with no API call.\n   *\n   * @param volumeId volume ID.\n   * @param name volume name.\n   * @param token volume auth token.\n   * @param domain domain for the volume API.\n   * @param debug whether to use debug mode.\n   */\n  constructor(\n    volumeId: string,\n    name: string,\n    token: string,\n    domain?: string,\n    debug?: boolean\n  ) {\n    this.volumeId = volumeId\n    this.name = name\n    this.token = token\n    this.domain = domain\n    this.debug = debug\n  }\n\n  /**\n   * Create a new volume.\n   *\n   * @param name name of the volume.\n   * @param opts connection options.\n   *\n   * @returns new Volume instance.\n   */\n  static async create(name: string, opts?: ConnectionOpts): Promise<Volume> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.POST('/volumes', {\n      body: {\n        name,\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    if (!res.data) {\n      throw new Error('Response data is missing')\n    }\n\n    return new Volume(\n      res.data.volumeID,\n      res.data.name,\n      res.data.token,\n      config.domain,\n      config.debug\n    )\n  }\n\n  /**\n   * Connect to an existing volume by ID.\n   *\n   * @param volumeId volume ID.\n   * @param opts connection options.\n   *\n   * @returns Volume instance.\n   */\n  static async connect(\n    volumeId: string,\n    opts?: ConnectionOpts\n  ): Promise<Volume> {\n    const config = new ConnectionConfig(opts)\n    const { name, token } = await Volume.getInfo(volumeId, opts)\n    return new Volume(volumeId, name, token, config.domain, config.debug)\n  }\n\n  /**\n   * Get volume information.\n   *\n   * @param volumeId volume ID.\n   * @param opts connection options.\n   *\n   * @returns volume information.\n   */\n  static async getInfo(\n    volumeId: string,\n    opts?: ConnectionOpts\n  ): Promise<VolumeAndToken> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.GET('/volumes/{volumeID}', {\n      params: {\n        path: {\n          volumeID: volumeId,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.response.status === 404) {\n      throw new NotFoundError(`Volume ${volumeId} not found`)\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    return {\n      volumeId: res.data!.volumeID,\n      name: res.data!.name,\n      token: res.data!.token,\n    }\n  }\n\n  /**\n   * List all volumes.\n   *\n   * @param opts connection options.\n   *\n   * @returns list of volume information.\n   */\n  static async list(opts?: ConnectionOpts): Promise<VolumeInfo[]> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.GET('/volumes', {\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    return (res.data ?? []).map((vol: ApiComponents['schemas']['Volume']) => ({\n      volumeId: vol.volumeID,\n      name: vol.name,\n    }))\n  }\n\n  /**\n   * Destroy a volume.\n   *\n   * @param volumeId volume ID.\n   * @param opts connection options.\n   */\n  static async destroy(\n    volumeId: string,\n    opts?: ConnectionOpts\n  ): Promise<boolean> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.DELETE('/volumes/{volumeID}', {\n      params: {\n        path: {\n          volumeID: volumeId,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.response.status === 404) {\n      return false\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    return true\n  }\n\n  /**\n   * List directory contents.\n   *\n   * @param path path to the directory.\n   * @param opts connection options.\n   * @param [opts.depth] number of layers deep to recurse into the directory (default: 1).\n   *\n   * @returns list of entries in the directory.\n   */\n  async list(\n    path: string,\n    opts?: VolumeApiOpts & { depth?: number }\n  ): Promise<VolumeEntryStat[]> {\n    const config = new VolumeConnectionConfig(this, opts)\n    const client = new VolumeApiClient(config)\n\n    const res = await client.api.GET('/volumecontent/{volumeID}/dir', {\n      params: {\n        path: {\n          volumeID: this.volumeId,\n        },\n        query: {\n          path,\n          depth: opts?.depth,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.response.status === 404) {\n      throw new NotFoundError(`Path ${path} not found`)\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    // VolumeDirectoryListing is an array according to the spec\n    const entries = Array.isArray(res.data) ? res.data : []\n    return entries.map(convertVolumeEntryStat)\n  }\n\n  /**\n   * Create a directory.\n   *\n   * @param path path to the directory to create.\n   * @param options directory creation options.\n   * @param opts connection options.\n   */\n  async makeDir(\n    path: string,\n    opts?: VolumeWriteOptions & VolumeApiOpts\n  ): Promise<VolumeEntryStat> {\n    const config = new VolumeConnectionConfig(this, opts)\n    const client = new VolumeApiClient(config)\n\n    const res = await client.api.POST('/volumecontent/{volumeID}/dir', {\n      params: {\n        path: {\n          volumeID: this.volumeId,\n        },\n        query: {\n          path,\n          uid: opts?.uid,\n          gid: opts?.gid,\n          mode: opts?.mode,\n          force: opts?.force,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.response.status === 404) {\n      throw new NotFoundError(`Path ${path} not found`)\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    if (!res.data) {\n      throw new Error('Response data is missing')\n    }\n\n    return convertVolumeEntryStat(\n      res.data as VolumeApiComponents['schemas']['VolumeEntryStat']\n    )\n  }\n\n  /**\n   * Get information about a file or directory.\n   *\n   * @param path path to the file or directory.\n   * @param opts connection options.\n   *\n   * @returns information about the entry.\n   */\n  async getInfo(path: string, opts?: VolumeApiOpts): Promise<VolumeEntryStat> {\n    const config = new VolumeConnectionConfig(this, opts)\n    const client = new VolumeApiClient(config)\n\n    const res = await client.api.GET('/volumecontent/{volumeID}/path', {\n      params: {\n        path: {\n          volumeID: this.volumeId,\n        },\n        query: {\n          path,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.response.status === 404) {\n      throw new NotFoundError(`Path ${path} not found`)\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    if (!res.data) {\n      throw new Error('Response data is missing')\n    }\n\n    return convertVolumeEntryStat(\n      res.data as VolumeApiComponents['schemas']['VolumeEntryStat']\n    )\n  }\n\n  /**\n   * Check whether a file or directory exists.\n   *\n   * Uses {@link getInfo} under the hood. Returns `true` if the path exists,\n   * `false` if it does not (404). Other errors are rethrown.\n   *\n   * @param path path to the file or directory.\n   * @param opts connection options.\n   *\n   * @returns `true` if the path exists, `false` otherwise.\n   */\n  async exists(path: string, opts?: VolumeApiOpts): Promise<boolean> {\n    try {\n      await this.getInfo(path, opts)\n      return true\n    } catch (err) {\n      if (err instanceof NotFoundError) {\n        return false\n      }\n      throw err\n    }\n  }\n\n  /**\n   * Update file or directory metadata.\n   *\n   * @param path path to the file or directory.\n   * @param metadata metadata to update (uid, gid, mode).\n   * @param opts connection options.\n   *\n   * @returns updated entry information.\n   */\n  async updateMetadata(\n    path: string,\n    metadata: VolumeMetadataOptions,\n    opts?: VolumeApiOpts\n  ): Promise<VolumeEntryStat> {\n    const config = new VolumeConnectionConfig(this, opts)\n    const client = new VolumeApiClient(config)\n\n    const res = await client.api.PATCH('/volumecontent/{volumeID}/path', {\n      params: {\n        path: {\n          volumeID: this.volumeId,\n        },\n        query: {\n          path,\n        },\n      },\n      body: {\n        uid: metadata.uid,\n        gid: metadata.gid,\n        mode: metadata.mode,\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.response.status === 404) {\n      throw new NotFoundError(`Path ${path} not found`)\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    if (!res.data) {\n      throw new Error('Response data is missing')\n    }\n\n    return convertVolumeEntryStat(\n      res.data as VolumeApiComponents['schemas']['VolumeEntryStat']\n    )\n  }\n\n  /**\n   * Read file content as a `string`.\n   *\n   * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.\n   *\n   * @param path path to the file.\n   * @param opts connection options.\n   * @param [opts.format] format of the file content—`text` by default.\n   *\n   * @returns file content as string\n   */\n  async readFile(\n    path: string,\n    opts?: VolumeApiOpts & { format?: 'text' }\n  ): Promise<string>\n  /**\n   * Read file content as a `Uint8Array`.\n   *\n   * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.\n   *\n   * @param path path to the file.\n   * @param opts connection options.\n   * @param [opts.format] format of the file content—`bytes`.\n   *\n   * @returns file content as `Uint8Array`\n   */\n  async readFile(\n    path: string,\n    opts?: VolumeApiOpts & { format: 'bytes' }\n  ): Promise<Uint8Array>\n  /**\n   * Read file content as a `Blob`.\n   *\n   * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.\n   *\n   * @param path path to the file.\n   * @param opts connection options.\n   * @param [opts.format] format of the file content—`blob`.\n   *\n   * @returns file content as `Blob`\n   */\n  async readFile(\n    path: string,\n    opts?: VolumeApiOpts & { format: 'blob' }\n  ): Promise<Blob>\n  /**\n   * Read file content as a `ReadableStream`.\n   *\n   * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.\n   *\n   * @param path path to the file.\n   * @param opts connection options.\n   * @param [opts.format] format of the file content—`stream`.\n   *\n   * @returns file content as `ReadableStream`\n   */\n  async readFile(\n    path: string,\n    opts?: VolumeApiOpts & { format: 'stream' }\n  ): Promise<ReadableStream<Uint8Array>>\n  async readFile(\n    path: string,\n    opts?: VolumeApiOpts & {\n      format?: 'text' | 'stream' | 'bytes' | 'blob'\n    }\n  ): Promise<unknown> {\n    const format = opts?.format ?? 'text'\n    const config = new VolumeConnectionConfig(this, opts)\n    const client = new VolumeApiClient(config)\n\n    const res = await client.api.GET('/volumecontent/{volumeID}/file', {\n      params: {\n        path: {\n          volumeID: this.volumeId,\n        },\n        query: {\n          path,\n        },\n      },\n      parseAs: format === 'bytes' ? 'arrayBuffer' : format,\n      signal: config.getSignal(\n        opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,\n        opts?.signal\n      ),\n    })\n\n    if (res.response.status === 404) {\n      throw new NotFoundError(`Path ${path} not found`)\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    if (format === 'bytes') {\n      return new Uint8Array(res.data as ArrayBuffer)\n    }\n\n    if (format === 'text') {\n      // When the file is empty, res.data is parsed as `{}`. This is a workaround to return an empty string.\n      if (res.response.headers.get('content-length') === '0') {\n        return ''\n      }\n      return typeof res.data === 'string' ? res.data : ''\n    }\n\n    return res.data\n  }\n\n  /**\n   * Write content to a file.\n   *\n   * Writing to a file that doesn't exist creates the file.\n   *\n   * Writing to a file that already exists overwrites the file.\n   *\n   * @param path path to the file.\n   * @param data data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`.\n   * @param options file creation options.\n   * @param opts connection options.\n   *\n   * @returns information about the written file\n   */\n  async writeFile(\n    path: string,\n    data: string | ArrayBuffer | Blob | ReadableStream<Uint8Array>,\n    opts?: VolumeWriteOptions & VolumeApiOpts\n  ): Promise<VolumeEntryStat> {\n    const config = new VolumeConnectionConfig(this, opts)\n    const client = new VolumeApiClient(config)\n\n    const blob = await toBlob(data)\n\n    const res = await client.api.PUT('/volumecontent/{volumeID}/file', {\n      params: {\n        path: {\n          volumeID: this.volumeId,\n        },\n        query: {\n          path,\n          uid: opts?.uid,\n          gid: opts?.gid,\n          mode: opts?.mode,\n          force: opts?.force,\n        },\n      },\n      bodySerializer: () => blob,\n      body: {} as any,\n      headers: {\n        'Content-Type': 'application/octet-stream',\n      },\n      signal: config.getSignal(\n        opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,\n        opts?.signal\n      ),\n    })\n\n    if (res.response.status === 404) {\n      throw new NotFoundError(`Path ${path} not found`)\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n\n    if (!res.data) {\n      throw new Error('Response data is missing')\n    }\n\n    return convertVolumeEntryStat(\n      res.data as VolumeApiComponents['schemas']['VolumeEntryStat']\n    )\n  }\n\n  /**\n   * Remove a file or directory.\n   *\n   * @param path path to the file or directory to remove.\n   * @param opts connection options.\n   */\n  async remove(path: string, opts?: VolumeApiOpts): Promise<void> {\n    const config = new VolumeConnectionConfig(this, opts)\n    const client = new VolumeApiClient(config)\n\n    const res = await client.api.DELETE('/volumecontent/{volumeID}/path', {\n      params: {\n        path: {\n          volumeID: this.volumeId,\n        },\n        query: {\n          path,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.response.status === 404) {\n      throw new NotFoundError(`Path ${path} not found`)\n    }\n\n    const err = handleApiError(res, VolumeError)\n    if (err) {\n      throw err\n    }\n  }\n}\n\nexport type {\n  VolumeInfo,\n  VolumeAndToken,\n  VolumeEntryStat,\n  VolumeMetadataOptions,\n  VolumeWriteOptions,\n} from './types'\n\nexport type { VolumeApiOpts, VolumeConnectionConfig } from './client'\nexport { VolumeFileType } from './types'\n","import { createConnectTransport } from '@connectrpc/connect-web'\n\nimport {\n  ConnectionConfig,\n  ConnectionOpts,\n  DEFAULT_SANDBOX_TIMEOUT_MS,\n  defaultUsername,\n  Username,\n} from '../connectionConfig'\nimport { EnvdApiClient, handleEnvdApiError } from '../envd/api'\nimport { createEnvdFetch, createEnvdRpcFetch } from '../envd/http2'\nimport { createRpcLogger } from '../logs'\nimport { Commands, Pty } from './commands'\nimport { Filesystem } from './filesystem'\nimport { Git } from './git'\nimport {\n  SandboxOpts,\n  SandboxConnectOpts,\n  SandboxMetricsOpts,\n  SandboxApi,\n  SandboxListOpts,\n  SandboxPaginator,\n  SnapshotListOpts,\n  SnapshotInfo,\n  SnapshotPaginator,\n  CreateSnapshotOpts,\n} from './sandboxApi'\nimport { getSignature } from './signature'\nimport { compareVersions } from 'compare-versions'\nimport { SandboxError } from '../errors'\nimport { ENVD_DEBUG_FALLBACK, ENVD_DEFAULT_USER } from '../envd/versions'\nimport { shellQuote } from '../utils'\n\n/**\n * Options for sandbox upload/download URL generation.\n */\nexport interface SandboxUrlOpts {\n  /**\n   * Use signature expiration for the URL.\n   * Optional parameter to set the expiration time for the signature in seconds.\n   */\n  useSignatureExpiration?: number\n\n  /**\n   * User that will be used to access the file.\n   */\n  user?: Username\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run git operations\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from 'e2b'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends SandboxApi {\n  protected static readonly defaultTemplate: string = 'base'\n  protected static readonly defaultMcpTemplate: string = 'mcp-gateway'\n  protected static readonly defaultSandboxTimeoutMs = DEFAULT_SANDBOX_TIMEOUT_MS\n\n  /**\n   * Module for interacting with the sandbox filesystem\n   */\n  readonly files: Filesystem\n  /**\n   * Module for running commands in the sandbox\n   */\n  readonly commands: Commands\n  /**\n   * Module for interacting with the sandbox pseudo-terminals\n   */\n  readonly pty: Pty\n  /**\n   * Module for running git operations in the sandbox\n   */\n  readonly git: Git\n\n  /**\n   * Unique identifier of the sandbox.\n   */\n  readonly sandboxId: string\n\n  /**\n   * Domain where the sandbox is hosted.\n   */\n  readonly sandboxDomain: string\n\n  /**\n   * Traffic access token for accessing sandbox services with restricted public traffic.\n   */\n  readonly trafficAccessToken?: string\n\n  protected readonly envdPort = 49983\n  protected readonly mcpPort = 50005\n\n  protected readonly connectionConfig: ConnectionConfig\n  protected readonly envdAccessToken?: string\n  private readonly envdApiUrl: string\n  private readonly envdApi: EnvdApiClient\n  private mcpToken?: string\n\n  /**\n   * Use {@link Sandbox.create} to create a new Sandbox instead.\n   *\n   * @hidden\n   * @hide\n   * @internal\n   * @access protected\n   */\n  constructor(\n    opts: SandboxConnectOpts & {\n      sandboxId: string\n      sandboxDomain?: string\n      envdVersion: string\n      envdAccessToken?: string\n      trafficAccessToken?: string\n    }\n  ) {\n    super()\n\n    this.connectionConfig = new ConnectionConfig(opts)\n\n    this.sandboxId = opts.sandboxId\n    this.sandboxDomain = opts.sandboxDomain ?? this.connectionConfig.domain\n\n    this.envdAccessToken = opts.envdAccessToken\n    this.trafficAccessToken = opts.trafficAccessToken\n    this.envdApiUrl = this.connectionConfig.getSandboxUrl(this.sandboxId, {\n      sandboxDomain: this.sandboxDomain,\n      envdPort: this.envdPort,\n    })\n\n    const sandboxHeaders = {\n      'E2b-Sandbox-Id': this.sandboxId,\n      'E2b-Sandbox-Port': this.envdPort.toString(),\n    }\n    const envdFetch = createEnvdFetch()\n    const envdRpcFetch = createEnvdRpcFetch()\n\n    const rpcTransport = createConnectTransport({\n      baseUrl: this.envdApiUrl,\n      useBinaryFormat: false,\n      interceptors: opts?.logger ? [createRpcLogger(opts.logger)] : undefined,\n      fetch: (url, options) => {\n        // Patch fetch to always use redirect: \"follow\"\n        // connect-web doesn't allow to configure redirect option - https://github.com/connectrpc/connect-es/pull/1082\n        // connect-web package uses redirect: \"error\" which is not supported in edge runtimes\n        // E2B endpoints should be safe to use with redirect: \"follow\" https://github.com/e2b-dev/E2B/issues/531#issuecomment-2779492867\n\n        const headers = new Headers(this.connectionConfig.headers)\n        new Headers(options?.headers).forEach((value, key) =>\n          headers.append(key, value)\n        )\n        new Headers(sandboxHeaders).forEach((value, key) =>\n          headers.append(key, value)\n        )\n\n        if (this.envdAccessToken) {\n          headers.append('X-Access-Token', this.envdAccessToken)\n        }\n\n        options = {\n          ...(options ?? {}),\n          headers: headers,\n          redirect: 'follow',\n        }\n\n        return envdRpcFetch(url, options)\n      },\n    })\n\n    this.envdApi = new EnvdApiClient(\n      {\n        apiUrl: this.envdApiUrl,\n        logger: opts?.logger,\n        accessToken: this.envdAccessToken,\n        headers: {\n          'User-Agent': this.connectionConfig.headers?.['User-Agent'] ?? '',\n          ...sandboxHeaders,\n          ...(this.envdAccessToken\n            ? { 'X-Access-Token': this.envdAccessToken }\n            : {}),\n        },\n        fetch: (request) => envdFetch(request),\n      },\n      {\n        version: opts.envdVersion,\n      }\n    )\n    this.files = new Filesystem(\n      rpcTransport,\n      this.envdApi,\n      this.connectionConfig\n    )\n    this.commands = new Commands(rpcTransport, this.connectionConfig, {\n      version: opts.envdVersion,\n    })\n    this.pty = new Pty(rpcTransport, this.connectionConfig, {\n      version: opts.envdVersion,\n    })\n    this.git = new Git(this.commands)\n  }\n\n  /**\n   * List all sandboxes.\n   *\n   * @param opts connection options.\n   *\n   * @returns paginator for listing sandboxes.\n   */\n  static list(opts?: SandboxListOpts): SandboxPaginator {\n    return new SandboxPaginator(opts)\n  }\n\n  /**\n   * Create a new sandbox from the default `base` sandbox template.\n   *\n   * @param opts connection options.\n   *\n   * @returns sandbox instance for the new sandbox.\n   *\n   * @example\n   * ```ts\n   * const sandbox = await Sandbox.create()\n   * ```\n   * @constructs {@link Sandbox}\n   */\n  static async create<S extends typeof Sandbox>(\n    this: S,\n    opts?: SandboxOpts\n  ): Promise<InstanceType<S>>\n\n  /**\n   * Create a new sandbox from the specified sandbox template.\n   *\n   * @param template sandbox template name or ID.\n   * @param opts connection options.\n   *\n   * @returns sandbox instance for the new sandbox.\n   *\n   * @example\n   * ```ts\n   * const sandbox = await Sandbox.create('<template-name-or-id>')\n   * ```\n   * @constructs {@link Sandbox}\n   */\n  static async create<S extends typeof Sandbox>(\n    this: S,\n    template: string,\n    opts?: SandboxOpts\n  ): Promise<InstanceType<S>>\n  static async create<S extends typeof Sandbox>(\n    this: S,\n    templateOrOpts?: SandboxOpts | string,\n    opts?: SandboxOpts\n  ): Promise<InstanceType<S>> {\n    const { template, sandboxOpts } =\n      typeof templateOrOpts === 'string'\n        ? {\n            template: templateOrOpts,\n            sandboxOpts: opts,\n          }\n        : {\n            template:\n              templateOrOpts?.template ??\n              (templateOrOpts?.mcp\n                ? this.defaultMcpTemplate\n                : this.defaultTemplate),\n            sandboxOpts: templateOrOpts,\n          }\n\n    const config = new ConnectionConfig(sandboxOpts)\n    if (config.debug) {\n      return new this({\n        sandboxId: 'debug_sandbox_id',\n        envdVersion: ENVD_DEBUG_FALLBACK,\n        ...config,\n      }) as InstanceType<S>\n    }\n\n    const sandboxInfo = await SandboxApi.createSandbox(\n      template,\n      sandboxOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,\n      sandboxOpts\n    )\n\n    const sandbox = new this({ ...sandboxInfo, ...config }) as InstanceType<S>\n\n    if (sandboxOpts?.mcp) {\n      sandbox.mcpToken = crypto.randomUUID()\n      const res = await sandbox.commands.run(\n        `mcp-gateway --config ${shellQuote(JSON.stringify(sandboxOpts.mcp))}`,\n        {\n          user: 'root',\n          envs: {\n            GATEWAY_ACCESS_TOKEN: sandbox.mcpToken ?? '',\n          },\n        }\n      )\n      if (res.exitCode !== 0) {\n        throw new Error(`Failed to start MCP gateway: ${res.stderr}`)\n      }\n    }\n\n    return sandbox\n  }\n\n  /**\n   * Connect to a sandbox. If the sandbox is paused, it will be automatically resumed.\n   * Sandbox must be either running or be paused.\n   *\n   * With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).\n   *\n   * @param sandboxId sandbox ID.\n   * @param opts connection options.\n   *\n   * @returns A running sandbox instance\n   *\n   * @example\n   * ```ts\n   * const sandbox = await Sandbox.create()\n   * const sandboxId = sandbox.sandboxId\n   *\n   * // Connect to the same sandbox.\n   * const sameSandbox = await Sandbox.connect(sandboxId)\n   * ```\n   */\n  static async connect<S extends typeof Sandbox>(\n    this: S,\n    sandboxId: string,\n    opts?: SandboxConnectOpts\n  ): Promise<InstanceType<S>> {\n    const sandbox = await SandboxApi.connectSandbox(sandboxId, opts)\n    const config = new ConnectionConfig(opts)\n\n    return new this({\n      sandboxId,\n      sandboxDomain: sandbox.sandboxDomain,\n      envdAccessToken: sandbox.envdAccessToken,\n      trafficAccessToken: sandbox.trafficAccessToken,\n      envdVersion: sandbox.envdVersion,\n      ...config,\n    }) as InstanceType<S>\n  }\n\n  /**\n   * Connect to a sandbox. If the sandbox is paused, it will be automatically resumed.\n   * Sandbox must be either running or be paused.\n   *\n   * With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).\n   *\n   * @param opts connection options.\n   *\n   * @returns A running sandbox instance\n   *\n   * @example\n   * ```ts\n   * const sandbox = await Sandbox.create()\n   * await sandbox.betaPause()\n   *\n   * // Connect to the same sandbox.\n   * const sameSandbox = await sandbox.connect()\n   * ```\n   */\n  async connect(opts?: SandboxConnectOpts): Promise<this> {\n    await SandboxApi.connectSandbox(this.sandboxId, this.resolveApiOpts(opts))\n\n    return this\n  }\n\n  /**\n   * Get the host address for the specified sandbox port.\n   * You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket.\n   *\n   * @param port number of the port in the sandbox.\n   *\n   * @returns host address of the sandbox port.\n   *\n   * @example\n   * ```ts\n   * const sandbox = await Sandbox.create()\n   * // Start an HTTP server\n   * await sandbox.commands.exec('python3 -m http.server 3000')\n   * // Get the hostname of the HTTP server\n   * const serverURL = sandbox.getHost(3000)\n   * ```\n   */\n  getHost(port: number) {\n    return this.connectionConfig.getHost(\n      this.sandboxId,\n      port,\n      this.sandboxDomain\n    )\n  }\n\n  /**\n   * Check if the sandbox is running.\n   *\n   * @returns `true` if the sandbox is running, `false` otherwise.\n   *\n   * @example\n   * ```ts\n   * const sandbox = await Sandbox.create()\n   * await sandbox.isRunning() // Returns true\n   *\n   * await sandbox.kill()\n   * await sandbox.isRunning() // Returns false\n   * ```\n   */\n  async isRunning(\n    opts?: Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>\n  ): Promise<boolean> {\n    const signal = this.connectionConfig.getSignal(\n      opts?.requestTimeoutMs,\n      opts?.signal\n    )\n\n    const res = await this.envdApi.api.GET('/health', {\n      signal,\n    })\n\n    if (res.response.status == 502) {\n      return false\n    }\n\n    const err = await handleEnvdApiError(res)\n    if (err) {\n      throw err\n    }\n\n    return true\n  }\n\n  /**\n   * Set the timeout of the sandbox.\n   *\n   * This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`.\n   * Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users.\n   *\n   * @param timeoutMs timeout in **milliseconds**.\n   * @param opts connection options.\n   */\n  async setTimeout(\n    timeoutMs: number,\n    opts?: Pick<SandboxOpts, 'requestTimeoutMs' | 'signal'>\n  ) {\n    if (this.connectionConfig.debug) {\n      // Skip timeout in debug mode\n      return\n    }\n\n    await SandboxApi.setTimeout(\n      this.sandboxId,\n      timeoutMs,\n      this.resolveApiOpts(opts)\n    )\n  }\n\n  /**\n   * Kill the sandbox.\n   *\n   * @param opts connection options.\n   */\n  async kill(opts?: Pick<SandboxOpts, 'requestTimeoutMs' | 'signal'>) {\n    if (this.connectionConfig.debug) {\n      // Skip killing in debug mode\n      return\n    }\n\n    await SandboxApi.kill(this.sandboxId, this.resolveApiOpts(opts))\n  }\n\n  /**\n   * Pause a sandbox by its ID.\n   *\n   * @param opts connection options.\n   *\n   * @returns sandbox ID that can be used to resume the sandbox.\n   *\n   * @example\n   * ```ts\n   * const sandbox = await Sandbox.create()\n   * await sandbox.pause()\n   * ```\n   */\n  async pause(opts?: ConnectionOpts): Promise<boolean> {\n    return await SandboxApi.pause(this.sandboxId, this.resolveApiOpts(opts))\n  }\n\n  /**\n   * @deprecated Use {@link Sandbox.pause} instead.\n   */\n  async betaPause(opts?: ConnectionOpts): Promise<boolean> {\n    return await SandboxApi.betaPause(this.sandboxId, this.resolveApiOpts(opts))\n  }\n\n  /**\n   * Create a snapshot of the sandbox's current state.\n   *\n   * The sandbox will be paused while the snapshot is being created.\n   * The snapshot can be used to create new sandboxes with the same filesystem and state.\n   * Snapshots are persistent and survive sandbox deletion.\n   *\n   * Use the returned `snapshotId` with `Sandbox.create(snapshotId)` to create a new sandbox from the snapshot.\n   *\n   * @param opts snapshot creation options including optional name and connection options.\n   *\n   * @returns snapshot information including the snapshot ID.\n   *\n   * @example\n   * ```ts\n   * const sandbox = await Sandbox.create()\n   * await sandbox.files.write('/app/state.json', '{\"step\": 1}')\n   *\n   * // Create a snapshot\n   * const snapshot = await sandbox.createSnapshot({ name: 'my-snapshot' })\n   *\n   * // Create a new sandbox from the snapshot\n   * const newSandbox = await Sandbox.create(snapshot.snapshotId)\n   * ```\n   */\n  async createSnapshot(opts?: CreateSnapshotOpts): Promise<SnapshotInfo> {\n    return await SandboxApi.createSnapshot(this.sandboxId, {\n      ...this.resolveApiOpts(opts),\n      name: opts?.name,\n    })\n  }\n\n  /**\n   * List all snapshots created from this sandbox.\n   *\n   * @param opts list options.\n   *\n   * @returns paginator for listing snapshots from this sandbox.\n   */\n  listSnapshots(opts?: Omit<SnapshotListOpts, 'sandboxId'>): SnapshotPaginator {\n    return SandboxApi.listSnapshots({\n      ...this.resolveApiOpts(opts),\n      sandboxId: this.sandboxId,\n    })\n  }\n\n  /**\n   *\n   * Get the MCP URL for the sandbox.\n   *\n   * @returns MCP URL for the sandbox.\n   */\n  getMcpUrl(): string {\n    return `https://${this.getHost(this.mcpPort)}/mcp`\n  }\n\n  /**\n   * Get the MCP token for the sandbox.\n   *\n   * @returns MCP token for the sandbox, or undefined if MCP is not enabled.\n   */\n  async getMcpToken(): Promise<string | undefined> {\n    if (!this.mcpToken) {\n      this.mcpToken = await this.files.read('/etc/mcp-gateway/.token', {\n        user: 'root',\n      })\n    }\n\n    return this.mcpToken\n  }\n\n  /**\n   * Get the URL to upload a file to the sandbox.\n   *\n   * You have to send a POST request to this URL with the file as multipart/form-data.\n   *\n   * @param path path to the file in the sandbox.\n   *\n   * @param opts download url options.\n   *\n   * @returns URL for uploading file.\n   */\n  async uploadUrl(path?: string, opts?: SandboxUrlOpts) {\n    opts = opts ?? {}\n\n    const useSignature = !!this.envdAccessToken\n\n    if (!useSignature && opts.useSignatureExpiration != undefined) {\n      throw new Error(\n        'Signature expiration can be used only when sandbox is created as secured.'\n      )\n    }\n\n    let username = opts.user\n    if (\n      username == undefined &&\n      compareVersions(this.envdApi.version, ENVD_DEFAULT_USER) < 0\n    ) {\n      username = defaultUsername\n    }\n\n    const filePath = path ?? ''\n    const fileUrl = this.fileUrl(filePath, username)\n\n    if (useSignature) {\n      const url = new URL(fileUrl)\n      const sig = await getSignature({\n        path: filePath,\n        operation: 'write',\n        user: username,\n        expirationInSeconds: opts.useSignatureExpiration,\n        envdAccessToken: this.envdAccessToken,\n      })\n\n      url.searchParams.set('signature', sig.signature)\n      if (sig.expiration) {\n        url.searchParams.set('signature_expiration', sig.expiration.toString())\n      }\n\n      return url.toString()\n    }\n\n    return fileUrl\n  }\n\n  /**\n   * Get the URL to download a file from the sandbox.\n   *\n   * @param path path to the file in the sandbox.\n   *\n   * @param opts download url options.\n   *\n   * @returns URL for downloading file.\n   */\n  async downloadUrl(path: string, opts?: SandboxUrlOpts) {\n    opts = opts ?? {}\n\n    const useSignature = !!this.envdAccessToken\n\n    if (!useSignature && opts.useSignatureExpiration != undefined) {\n      throw new Error(\n        'Signature expiration can be used only when sandbox is created as secured.'\n      )\n    }\n\n    let username = opts.user\n    if (\n      username == undefined &&\n      compareVersions(this.envdApi.version, ENVD_DEFAULT_USER) < 0\n    ) {\n      username = defaultUsername\n    }\n\n    const fileUrl = this.fileUrl(path, username)\n\n    if (useSignature) {\n      const url = new URL(fileUrl)\n      const sig = await getSignature({\n        path,\n        operation: 'read',\n        user: username,\n        expirationInSeconds: opts.useSignatureExpiration,\n        envdAccessToken: this.envdAccessToken,\n      })\n\n      url.searchParams.set('signature', sig.signature)\n      if (sig.expiration) {\n        url.searchParams.set('signature_expiration', sig.expiration.toString())\n      }\n\n      return url.toString()\n    }\n\n    return fileUrl\n  }\n\n  /**\n   * Get sandbox information like sandbox ID, template, metadata, started at/end at date.\n   *\n   * @param opts connection options.\n   *\n   * @returns information about the sandbox\n   */\n  async getInfo(opts?: Pick<SandboxOpts, 'requestTimeoutMs' | 'signal'>) {\n    return await SandboxApi.getInfo(this.sandboxId, this.resolveApiOpts(opts))\n  }\n\n  /**\n   * Get the metrics of the sandbox.\n   *\n   * @param opts connection options.\n   *\n   * @returns  List of sandbox metrics containing CPU, memory and disk usage information.\n   */\n  async getMetrics(opts?: SandboxMetricsOpts) {\n    if (this.envdApi.version) {\n      if (compareVersions(this.envdApi.version, '0.1.5') < 0) {\n        throw new SandboxError(\n          'You need to update the template to use the new SDK. ' +\n            'You can do this by running `e2b template build` in the directory with the template.'\n        )\n      }\n\n      if (compareVersions(this.envdApi.version, '0.2.4') < 0) {\n        this.connectionConfig.logger?.warn?.(\n          'Disk metrics are not supported in this version of the sandbox, please rebuild the template to get disk metrics.'\n        )\n      }\n    }\n\n    return await SandboxApi.getMetrics(\n      this.sandboxId,\n      this.resolveApiOpts(opts)\n    )\n  }\n\n  private resolveApiOpts<T extends ConnectionOpts>(\n    opts?: T\n  ): ConnectionOpts & T {\n    return {\n      ...this.connectionConfig,\n      ...(opts ?? {}),\n    } as ConnectionOpts & T\n  }\n\n  private fileUrl(path: string | undefined, username: string | undefined) {\n    const url = new URL('/files', this.envdApiUrl)\n\n    if (username) {\n      url.searchParams.set('username', username)\n    }\n    if (path) {\n      url.searchParams.set('path', path)\n    }\n\n    return url.toString()\n  }\n}\n","import { runtime } from '../utils'\nimport {\n  loadUndici,\n  toUndiciRequestInput,\n  type UndiciModule,\n  type UndiciRequestInit,\n} from '../undici'\n\ntype EnvdFetchOptions = {\n  connectionLimit?: number\n  loadUndici?: () => Promise<UndiciModule | undefined>\n}\n\nlet envdFetch: typeof fetch | undefined\nlet envdRpcFetch: typeof fetch | undefined\nlet hasWarnedUndiciFallback = false\n\nexport function createEnvdFetchForRuntime(\n  currentRuntime = runtime,\n  options: EnvdFetchOptions = { connectionLimit: 1 }\n): typeof fetch {\n  if (currentRuntime !== 'node') {\n    return fetch\n  }\n\n  let fetcherPromise: Promise<typeof fetch> | undefined\n\n  return (async (input, init) => {\n    fetcherPromise ??= buildEnvdFetcher(options)\n    const fetcher = await fetcherPromise\n\n    return fetcher(input, init)\n  }) as typeof fetch\n}\n\nasync function buildEnvdFetcher(\n  options: EnvdFetchOptions\n): Promise<typeof fetch> {\n  const undici = await (options.loadUndici ?? loadUndici)()\n\n  if (!undici) {\n    warnUndiciFallback()\n\n    return fetch\n  }\n\n  const { Agent, fetch: undiciFetch } = undici\n  const dispatcherOptions: { allowH2: true; connections?: number } = {\n    allowH2: true,\n  }\n  if (options.connectionLimit !== undefined) {\n    dispatcherOptions.connections = options.connectionLimit\n  }\n\n  const dispatcher = new Agent(dispatcherOptions)\n  const fetchWithDispatcher = undiciFetch as unknown as (\n    input: RequestInfo | URL,\n    init?: UndiciRequestInit\n  ) => Promise<Response>\n\n  return ((input, init) => {\n    const request = toUndiciRequestInput(input, init)\n\n    return fetchWithDispatcher(request.input, {\n      ...request.init,\n      dispatcher,\n    })\n  }) as typeof fetch\n}\n\nfunction warnUndiciFallback() {\n  if (hasWarnedUndiciFallback) {\n    return\n  }\n\n  hasWarnedUndiciFallback = true\n  console.warn(\n    'Failed to load undici for envd HTTP/2 transport; falling back to global fetch.'\n  )\n}\n\nexport function createEnvdFetch(): typeof fetch {\n  if (envdFetch) {\n    return envdFetch\n  }\n\n  // Keep one origin connection for short envd REST calls. If ALPN falls back\n  // to h1, this favors connection pressure over per-sandbox throughput.\n  envdFetch = createEnvdFetchForRuntime(runtime)\n\n  return envdFetch\n}\n\nexport function createEnvdRpcFetch(): typeof fetch {\n  if (envdRpcFetch) {\n    return envdRpcFetch\n  }\n\n  // RPC streams can stay open while follow-up RPCs run against the same\n  // sandbox, so they cannot share the REST client's single-connection cap.\n  envdRpcFetch = createEnvdFetchForRuntime(runtime, {})\n\n  return envdRpcFetch\n}\n","import {\n  Client,\n  Code,\n  ConnectError,\n  Transport,\n  createClient,\n} from '@connectrpc/connect'\n\nimport { compareVersions } from 'compare-versions'\nimport {\n  ConnectionConfig,\n  ConnectionOpts,\n  KEEPALIVE_PING_HEADER,\n  KEEPALIVE_PING_INTERVAL_SEC,\n  setupRequestController,\n  Username,\n} from '../../connectionConfig'\nimport { handleProcessStartEvent } from '../../envd/api'\nimport {\n  Process as ProcessService,\n  Signal,\n} from '../../envd/process/process_pb'\nimport { authenticationHeader, handleRpcError } from '../../envd/rpc'\nimport { ENVD_COMMANDS_STDIN, ENVD_ENVD_CLOSE } from '../../envd/versions'\nimport { SandboxError } from '../../errors'\nimport { CommandHandle, CommandResult } from './commandHandle'\nexport { Pty } from './pty'\n\n/**\n * Options for sending a command request.\n */\nexport interface CommandRequestOpts\n  extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>> {}\n\n/**\n * Options for starting a new command.\n */\nexport interface CommandStartOpts extends CommandRequestOpts {\n  /**\n   * If true, starts command in the background and the method returns immediately.\n   * You can use {@link CommandHandle.wait} to wait for the command to finish.\n   */\n  background?: boolean\n  /**\n   * Working directory for the command.\n   *\n   * @default // home directory of the user used to start the command\n   */\n  cwd?: string\n  /**\n   * User to run the command as.\n   *\n   * @default `default Sandbox user (as specified in the template)`\n   */\n  user?: Username\n  /**\n   * Environment variables used for the command.\n   *\n   * This overrides the default environment variables from `Sandbox` constructor.\n   *\n   * @default `{}`\n   */\n  envs?: Record<string, string>\n  /**\n   * Callback for command stdout output.\n   */\n  onStdout?: (data: string) => void | Promise<void>\n  /**\n   * Callback for command stderr output.\n   */\n  onStderr?: (data: string) => void | Promise<void>\n  /**\n   * If true, command stdin is kept open and you can send data to it using {@link Commands.sendStdin} or {@link CommandHandle.sendStdin}.\n   * @default false\n   */\n  stdin?: boolean\n  /**\n   * Timeout for the command in **milliseconds**.\n   *\n   * @default 60_000 // 60 seconds\n   */\n  timeoutMs?: number\n}\n\n/**\n * Options for connecting to a command.\n */\nexport type CommandConnectOpts = Pick<\n  CommandStartOpts,\n  'onStderr' | 'onStdout' | 'timeoutMs'\n> &\n  CommandRequestOpts\n\n/**\n * Information about a command, PTY session or start command running in the sandbox as process.\n */\nexport interface ProcessInfo {\n  /**\n   * Process ID.\n   */\n  pid: number\n  /**\n   * Custom tag used for identifying special commands like start command in the custom template.\n   */\n  tag?: string\n  /**\n   * Command that was executed.\n   */\n  cmd: string\n  /**\n   * Command arguments.\n   */\n  args: string[]\n  /**\n   * Environment variables used for the command.\n   */\n  envs: Record<string, string>\n  /**\n   * Executed command working directory.\n   */\n  cwd?: string\n}\n\n/**\n * Module for starting and interacting with commands in the sandbox.\n */\nexport class Commands {\n  protected readonly rpc: Client<typeof ProcessService>\n\n  private readonly defaultProcessConnectionTimeout = 60_000 // 60 seconds\n  private readonly envdVersion: string\n\n  constructor(\n    transport: Transport,\n    private readonly connectionConfig: ConnectionConfig,\n    metadata: {\n      version: string\n    }\n  ) {\n    this.rpc = createClient(ProcessService, transport)\n    this.envdVersion = metadata.version\n  }\n\n  /**\n   * @hidden\n   * @internal\n   */\n  get supportsStdinClose(): boolean {\n    return compareVersions(this.envdVersion, ENVD_ENVD_CLOSE) >= 0\n  }\n\n  /**\n   * List all running commands and PTY sessions.\n   *\n   * @param opts connection options.\n   *\n   * @returns list of running commands and PTY sessions.\n   */\n  async list(opts?: CommandRequestOpts): Promise<ProcessInfo[]> {\n    try {\n      const res = await this.rpc.list(\n        {},\n        {\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n\n      return res.processes.map((p) => ({\n        pid: p.pid,\n        ...(p.tag && { tag: p.tag }),\n        args: p.config!.args,\n        envs: p.config!.envs,\n        cmd: p.config!.cmd,\n        ...(p.config!.cwd && { cwd: p.config!.cwd }),\n      }))\n    } catch (err) {\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * Send data to command stdin.\n   *\n   * @param pid process ID of the command. You can get the list of running commands using {@link Commands.list}.\n   * @param data data to send to the command.\n   * @param opts connection options.\n   */\n  async sendStdin(\n    pid: number,\n    data: string | Uint8Array,\n    opts?: CommandRequestOpts\n  ): Promise<void> {\n    try {\n      const payload =\n        typeof data === 'string' ? new TextEncoder().encode(data) : data\n\n      await this.rpc.sendInput(\n        {\n          process: {\n            selector: {\n              case: 'pid',\n              value: pid,\n            },\n          },\n          input: {\n            input: {\n              case: 'stdin',\n              value: payload,\n            },\n          },\n        },\n        {\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n    } catch (err) {\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * @hidden\n   * @internal\n   */\n  async closeStdin(pid: number, opts?: CommandRequestOpts): Promise<void> {\n    if (!this.supportsStdinClose) {\n      throw new SandboxError(\n        `Sandbox envd version ${this.envdVersion} doesn't support closeStdin. Please rebuild your template to pick up the latest sandbox version.`\n      )\n    }\n\n    try {\n      await this.rpc.closeStdin(\n        {\n          process: {\n            selector: {\n              case: 'pid',\n              value: pid,\n            },\n          },\n        },\n        {\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n    } catch (err) {\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * Kill a running command specified by its process ID.\n   * It uses `SIGKILL` signal to kill the command.\n   *\n   * @param pid process ID of the command. You can get the list of running commands using {@link Commands.list}.\n   * @param opts connection options.\n   *\n   * @returns `true` if the command was killed, `false` if the command was not found.\n   */\n  async kill(pid: number, opts?: CommandRequestOpts): Promise<boolean> {\n    try {\n      await this.rpc.sendSignal(\n        {\n          process: {\n            selector: {\n              case: 'pid',\n              value: pid,\n            },\n          },\n          signal: Signal.SIGKILL,\n        },\n        {\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n\n      return true\n    } catch (err) {\n      if (err instanceof ConnectError) {\n        if (err.code === Code.NotFound) {\n          return false\n        }\n      }\n\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * Connect to a running command.\n   * You can use {@link CommandHandle.wait} to wait for the command to finish and get execution results.\n   *\n   * @param pid process ID of the command to connect to. You can get the list of running commands using {@link Commands.list}.\n   * @param opts connection options.\n   *\n   * @returns `CommandHandle` handle to interact with the running command.\n   */\n  async connect(\n    pid: number,\n    opts?: CommandConnectOpts\n  ): Promise<CommandHandle> {\n    const requestTimeoutMs =\n      opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n    const { controller, clearStartTimeout, cleanup } = setupRequestController(\n      requestTimeoutMs,\n      opts?.signal\n    )\n\n    const events = this.rpc.connect(\n      {\n        process: {\n          selector: {\n            case: 'pid',\n            value: pid,\n          },\n        },\n      },\n      {\n        signal: controller.signal,\n        headers: {\n          [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),\n        },\n        timeoutMs: opts?.timeoutMs ?? this.defaultProcessConnectionTimeout,\n      }\n    )\n\n    try {\n      const pid = await handleProcessStartEvent(events)\n      clearStartTimeout()\n\n      return new CommandHandle(\n        pid,\n        cleanup,\n        () => this.kill(pid),\n        events,\n        opts?.onStdout,\n        opts?.onStderr,\n        undefined\n      )\n    } catch (err) {\n      cleanup()\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * Start a new command and wait until it finishes executing.\n   *\n   * @param cmd command to execute.\n   * @param opts options for starting the command.\n   *\n   * @returns `CommandResult` result of the command execution.\n   */\n  async run(\n    cmd: string,\n    opts?: CommandStartOpts & { background?: false }\n  ): Promise<CommandResult>\n\n  /**\n   * Start a new command in the background.\n   * You can use {@link CommandHandle.wait} to wait for the command to finish and get its result.\n   *\n   * @param cmd command to execute.\n   * @param opts options for starting the command\n   *\n   * @returns `CommandHandle` handle to interact with the running command.\n   */\n  async run(\n    cmd: string,\n    opts: CommandStartOpts & { background: true }\n  ): Promise<CommandHandle>\n\n  // NOTE - The following overload seems redundant, but it's required to make the type inference work correctly.\n\n  /**\n   * Start a new command.\n   *\n   * @param cmd command to execute.\n   * @param opts options for starting the command.\n   *   - `opts.background: true` - runs in background, returns `CommandHandle`\n   *   - `opts.background: false | undefined` - waits for completion, returns `CommandResult`\n   *\n   * @returns Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`).\n   */\n  async run(\n    cmd: string,\n    opts?: CommandStartOpts & { background?: boolean }\n  ): Promise<CommandHandle | CommandResult>\n  async run(\n    cmd: string,\n    opts?: CommandStartOpts & { background?: boolean }\n  ): Promise<CommandHandle | CommandResult> {\n    const proc = await this.start(cmd, opts)\n\n    return opts?.background ? proc : proc.wait()\n  }\n\n  private async start(\n    cmd: string,\n    opts?: CommandStartOpts\n  ): Promise<CommandHandle> {\n    if (\n      opts?.stdin === false &&\n      compareVersions(this.envdVersion, ENVD_COMMANDS_STDIN) < 0\n    ) {\n      throw new SandboxError(\n        `Sandbox envd version ${this.envdVersion} can't specify stdin, it's always turned on. Please rebuild your template if you need this feature.`\n      )\n    }\n\n    const requestTimeoutMs =\n      opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n    const { controller, clearStartTimeout, cleanup } = setupRequestController(\n      requestTimeoutMs,\n      opts?.signal\n    )\n\n    const events = this.rpc.start(\n      {\n        process: {\n          cmd: '/bin/bash',\n          cwd: opts?.cwd,\n          envs: opts?.envs,\n          args: ['-l', '-c', cmd],\n        },\n        stdin: opts?.stdin || false,\n      },\n      {\n        headers: {\n          ...authenticationHeader(this.envdVersion, opts?.user),\n          [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),\n        },\n        signal: controller.signal,\n        timeoutMs: opts?.timeoutMs ?? this.defaultProcessConnectionTimeout,\n      }\n    )\n\n    try {\n      const pid = await handleProcessStartEvent(events)\n      clearStartTimeout()\n\n      return new CommandHandle(\n        pid,\n        cleanup,\n        () => this.kill(pid),\n        events,\n        opts?.onStdout,\n        opts?.onStderr,\n        undefined\n      )\n    } catch (err) {\n      cleanup()\n      throw handleRpcError(err)\n    }\n  }\n}\n","// @generated by protoc-gen-es v2.6.2 with parameter \"target=ts\"\n// @generated from file process/process.proto (package process, syntax proto3)\n/* eslint-disable */\n\nimport type {\n  GenEnum,\n  GenFile,\n  GenMessage,\n  GenService,\n} from '@bufbuild/protobuf/codegenv2'\nimport {\n  enumDesc,\n  fileDesc,\n  messageDesc,\n  serviceDesc,\n} from '@bufbuild/protobuf/codegenv2'\nimport type { Message } from '@bufbuild/protobuf'\n\n/**\n * Describes the file process/process.proto.\n */\nexport const file_process_process: GenFile =\n  /*@__PURE__*/\n  fileDesc(\n    'ChVwcm9jZXNzL3Byb2Nlc3MucHJvdG8SB3Byb2Nlc3MiSgoDUFRZEh8KBHNpemUYASABKAsyES5wcm9jZXNzLlBUWS5TaXplGiIKBFNpemUSDAoEY29scxgBIAEoDRIMCgRyb3dzGAIgASgNIqEBCg1Qcm9jZXNzQ29uZmlnEgsKA2NtZBgBIAEoCRIMCgRhcmdzGAIgAygJEi4KBGVudnMYAyADKAsyIC5wcm9jZXNzLlByb2Nlc3NDb25maWcuRW52c0VudHJ5EhAKA2N3ZBgEIAEoCUgAiAEBGisKCUVudnNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBQgYKBF9jd2QiDQoLTGlzdFJlcXVlc3QiXAoLUHJvY2Vzc0luZm8SJgoGY29uZmlnGAEgASgLMhYucHJvY2Vzcy5Qcm9jZXNzQ29uZmlnEgsKA3BpZBgCIAEoDRIQCgN0YWcYAyABKAlIAIgBAUIGCgRfdGFnIjcKDExpc3RSZXNwb25zZRInCglwcm9jZXNzZXMYASADKAsyFC5wcm9jZXNzLlByb2Nlc3NJbmZvIpcBCgxTdGFydFJlcXVlc3QSJwoHcHJvY2VzcxgBIAEoCz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nexport type PTY = Message<'process.PTY'> & {\n  /**\n   * @generated from field: process.PTY.Size size = 1;\n   */\n  size?: PTY_Size\n}\n\n/**\n * Describes the message process.PTY.\n * Use `create(PTYSchema)` to create a new message.\n */\nexport const PTYSchema: GenMessage<PTY> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 0)\n\n/**\n * @generated from message process.PTY.Size\n */\nexport type PTY_Size = Message<'process.PTY.Size'> & {\n  /**\n   * @generated from field: uint32 cols = 1;\n   */\n  cols: number\n\n  /**\n   * @generated from field: uint32 rows = 2;\n   */\n  rows: number\n}\n\n/**\n * Describes the message process.PTY.Size.\n * Use `create(PTY_SizeSchema)` to create a new message.\n */\nexport const PTY_SizeSchema: GenMessage<PTY_Size> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 0, 0)\n\n/**\n * @generated from message process.ProcessConfig\n */\nexport type ProcessConfig = Message<'process.ProcessConfig'> & {\n  /**\n   * @generated from field: string cmd = 1;\n   */\n  cmd: string\n\n  /**\n   * @generated from field: repeated string args = 2;\n   */\n  args: string[]\n\n  /**\n   * @generated from field: map<string, string> envs = 3;\n   */\n  envs: { [key: string]: string }\n\n  /**\n   * @generated from field: optional string cwd = 4;\n   */\n  cwd?: string\n}\n\n/**\n * Describes the message process.ProcessConfig.\n * Use `create(ProcessConfigSchema)` to create a new message.\n */\nexport const ProcessConfigSchema: GenMessage<ProcessConfig> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 1)\n\n/**\n * @generated from message process.ListRequest\n */\nexport type ListRequest = Message<'process.ListRequest'> & {}\n\n/**\n * Describes the message process.ListRequest.\n * Use `create(ListRequestSchema)` to create a new message.\n */\nexport const ListRequestSchema: GenMessage<ListRequest> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 2)\n\n/**\n * @generated from message process.ProcessInfo\n */\nexport type ProcessInfo = Message<'process.ProcessInfo'> & {\n  /**\n   * @generated from field: process.ProcessConfig config = 1;\n   */\n  config?: ProcessConfig\n\n  /**\n   * @generated from field: uint32 pid = 2;\n   */\n  pid: number\n\n  /**\n   * @generated from field: optional string tag = 3;\n   */\n  tag?: string\n}\n\n/**\n * Describes the message process.ProcessInfo.\n * Use `create(ProcessInfoSchema)` to create a new message.\n */\nexport const ProcessInfoSchema: GenMessage<ProcessInfo> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 3)\n\n/**\n * @generated from message process.ListResponse\n */\nexport type ListResponse = Message<'process.ListResponse'> & {\n  /**\n   * @generated from field: repeated process.ProcessInfo processes = 1;\n   */\n  processes: ProcessInfo[]\n}\n\n/**\n * Describes the message process.ListResponse.\n * Use `create(ListResponseSchema)` to create a new message.\n */\nexport const ListResponseSchema: GenMessage<ListResponse> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 4)\n\n/**\n * @generated from message process.StartRequest\n */\nexport type StartRequest = Message<'process.StartRequest'> & {\n  /**\n   * @generated from field: process.ProcessConfig process = 1;\n   */\n  process?: ProcessConfig\n\n  /**\n   * @generated from field: optional process.PTY pty = 2;\n   */\n  pty?: PTY\n\n  /**\n   * @generated from field: optional string tag = 3;\n   */\n  tag?: string\n\n  /**\n   * @generated from field: optional bool stdin = 4;\n   */\n  stdin?: boolean\n}\n\n/**\n * Describes the message process.StartRequest.\n * Use `create(StartRequestSchema)` to create a new message.\n */\nexport const StartRequestSchema: GenMessage<StartRequest> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 5)\n\n/**\n * @generated from message process.UpdateRequest\n */\nexport type UpdateRequest = Message<'process.UpdateRequest'> & {\n  /**\n   * @generated from field: process.ProcessSelector process = 1;\n   */\n  process?: ProcessSelector\n\n  /**\n   * @generated from field: optional process.PTY pty = 2;\n   */\n  pty?: PTY\n}\n\n/**\n * Describes the message process.UpdateRequest.\n * Use `create(UpdateRequestSchema)` to create a new message.\n */\nexport const UpdateRequestSchema: GenMessage<UpdateRequest> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 6)\n\n/**\n * @generated from message process.UpdateResponse\n */\nexport type UpdateResponse = Message<'process.UpdateResponse'> & {}\n\n/**\n * Describes the message process.UpdateResponse.\n * Use `create(UpdateResponseSchema)` to create a new message.\n */\nexport const UpdateResponseSchema: GenMessage<UpdateResponse> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 7)\n\n/**\n * @generated from message process.ProcessEvent\n */\nexport type ProcessEvent = Message<'process.ProcessEvent'> & {\n  /**\n   * @generated from oneof process.ProcessEvent.event\n   */\n  event:\n    | {\n        /**\n         * @generated from field: process.ProcessEvent.StartEvent start = 1;\n         */\n        value: ProcessEvent_StartEvent\n        case: 'start'\n      }\n    | {\n        /**\n         * @generated from field: process.ProcessEvent.DataEvent data = 2;\n         */\n        value: ProcessEvent_DataEvent\n        case: 'data'\n      }\n    | {\n        /**\n         * @generated from field: process.ProcessEvent.EndEvent end = 3;\n         */\n        value: ProcessEvent_EndEvent\n        case: 'end'\n      }\n    | {\n        /**\n         * @generated from field: process.ProcessEvent.KeepAlive keepalive = 4;\n         */\n        value: ProcessEvent_KeepAlive\n        case: 'keepalive'\n      }\n    | { case: undefined; value?: undefined }\n}\n\n/**\n * Describes the message process.ProcessEvent.\n * Use `create(ProcessEventSchema)` to create a new message.\n */\nexport const ProcessEventSchema: GenMessage<ProcessEvent> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 8)\n\n/**\n * @generated from message process.ProcessEvent.StartEvent\n */\nexport type ProcessEvent_StartEvent =\n  Message<'process.ProcessEvent.StartEvent'> & {\n    /**\n     * @generated from field: uint32 pid = 1;\n     */\n    pid: number\n  }\n\n/**\n * Describes the message process.ProcessEvent.StartEvent.\n * Use `create(ProcessEvent_StartEventSchema)` to create a new message.\n */\nexport const ProcessEvent_StartEventSchema: GenMessage<ProcessEvent_StartEvent> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 8, 0)\n\n/**\n * @generated from message process.ProcessEvent.DataEvent\n */\nexport type ProcessEvent_DataEvent =\n  Message<'process.ProcessEvent.DataEvent'> & {\n    /**\n     * @generated from oneof process.ProcessEvent.DataEvent.output\n     */\n    output:\n      | {\n          /**\n           * @generated from field: bytes stdout = 1;\n           */\n          value: Uint8Array\n          case: 'stdout'\n        }\n      | {\n          /**\n           * @generated from field: bytes stderr = 2;\n           */\n          value: Uint8Array\n          case: 'stderr'\n        }\n      | {\n          /**\n           * @generated from field: bytes pty = 3;\n           */\n          value: Uint8Array\n          case: 'pty'\n        }\n      | { case: undefined; value?: undefined }\n  }\n\n/**\n * Describes the message process.ProcessEvent.DataEvent.\n * Use `create(ProcessEvent_DataEventSchema)` to create a new message.\n */\nexport const ProcessEvent_DataEventSchema: GenMessage<ProcessEvent_DataEvent> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 8, 1)\n\n/**\n * @generated from message process.ProcessEvent.EndEvent\n */\nexport type ProcessEvent_EndEvent = Message<'process.ProcessEvent.EndEvent'> & {\n  /**\n   * @generated from field: sint32 exit_code = 1;\n   */\n  exitCode: number\n\n  /**\n   * @generated from field: bool exited = 2;\n   */\n  exited: boolean\n\n  /**\n   * @generated from field: string status = 3;\n   */\n  status: string\n\n  /**\n   * @generated from field: optional string error = 4;\n   */\n  error?: string\n}\n\n/**\n * Describes the message process.ProcessEvent.EndEvent.\n * Use `create(ProcessEvent_EndEventSchema)` to create a new message.\n */\nexport const ProcessEvent_EndEventSchema: GenMessage<ProcessEvent_EndEvent> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 8, 2)\n\n/**\n * @generated from message process.ProcessEvent.KeepAlive\n */\nexport type ProcessEvent_KeepAlive =\n  Message<'process.ProcessEvent.KeepAlive'> & {}\n\n/**\n * Describes the message process.ProcessEvent.KeepAlive.\n * Use `create(ProcessEvent_KeepAliveSchema)` to create a new message.\n */\nexport const ProcessEvent_KeepAliveSchema: GenMessage<ProcessEvent_KeepAlive> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 8, 3)\n\n/**\n * @generated from message process.StartResponse\n */\nexport type StartResponse = Message<'process.StartResponse'> & {\n  /**\n   * @generated from field: process.ProcessEvent event = 1;\n   */\n  event?: ProcessEvent\n}\n\n/**\n * Describes the message process.StartResponse.\n * Use `create(StartResponseSchema)` to create a new message.\n */\nexport const StartResponseSchema: GenMessage<StartResponse> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 9)\n\n/**\n * @generated from message process.ConnectResponse\n */\nexport type ConnectResponse = Message<'process.ConnectResponse'> & {\n  /**\n   * @generated from field: process.ProcessEvent event = 1;\n   */\n  event?: ProcessEvent\n}\n\n/**\n * Describes the message process.ConnectResponse.\n * Use `create(ConnectResponseSchema)` to create a new message.\n */\nexport const ConnectResponseSchema: GenMessage<ConnectResponse> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 10)\n\n/**\n * @generated from message process.SendInputRequest\n */\nexport type SendInputRequest = Message<'process.SendInputRequest'> & {\n  /**\n   * @generated from field: process.ProcessSelector process = 1;\n   */\n  process?: ProcessSelector\n\n  /**\n   * @generated from field: process.ProcessInput input = 2;\n   */\n  input?: ProcessInput\n}\n\n/**\n * Describes the message process.SendInputRequest.\n * Use `create(SendInputRequestSchema)` to create a new message.\n */\nexport const SendInputRequestSchema: GenMessage<SendInputRequest> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 11)\n\n/**\n * @generated from message process.SendInputResponse\n */\nexport type SendInputResponse = Message<'process.SendInputResponse'> & {}\n\n/**\n * Describes the message process.SendInputResponse.\n * Use `create(SendInputResponseSchema)` to create a new message.\n */\nexport const SendInputResponseSchema: GenMessage<SendInputResponse> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 12)\n\n/**\n * @generated from message process.ProcessInput\n */\nexport type ProcessInput = Message<'process.ProcessInput'> & {\n  /**\n   * @generated from oneof process.ProcessInput.input\n   */\n  input:\n    | {\n        /**\n         * @generated from field: bytes stdin = 1;\n         */\n        value: Uint8Array\n        case: 'stdin'\n      }\n    | {\n        /**\n         * @generated from field: bytes pty = 2;\n         */\n        value: Uint8Array\n        case: 'pty'\n      }\n    | { case: undefined; value?: undefined }\n}\n\n/**\n * Describes the message process.ProcessInput.\n * Use `create(ProcessInputSchema)` to create a new message.\n */\nexport const ProcessInputSchema: GenMessage<ProcessInput> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 13)\n\n/**\n * @generated from message process.StreamInputRequest\n */\nexport type StreamInputRequest = Message<'process.StreamInputRequest'> & {\n  /**\n   * @generated from oneof process.StreamInputRequest.event\n   */\n  event:\n    | {\n        /**\n         * @generated from field: process.StreamInputRequest.StartEvent start = 1;\n         */\n        value: StreamInputRequest_StartEvent\n        case: 'start'\n      }\n    | {\n        /**\n         * @generated from field: process.StreamInputRequest.DataEvent data = 2;\n         */\n        value: StreamInputRequest_DataEvent\n        case: 'data'\n      }\n    | {\n        /**\n         * @generated from field: process.StreamInputRequest.KeepAlive keepalive = 3;\n         */\n        value: StreamInputRequest_KeepAlive\n        case: 'keepalive'\n      }\n    | { case: undefined; value?: undefined }\n}\n\n/**\n * Describes the message process.StreamInputRequest.\n * Use `create(StreamInputRequestSchema)` to create a new message.\n */\nexport const StreamInputRequestSchema: GenMessage<StreamInputRequest> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 14)\n\n/**\n * @generated from message process.StreamInputRequest.StartEvent\n */\nexport type StreamInputRequest_StartEvent =\n  Message<'process.StreamInputRequest.StartEvent'> & {\n    /**\n     * @generated from field: process.ProcessSelector process = 1;\n     */\n    process?: ProcessSelector\n  }\n\n/**\n * Describes the message process.StreamInputRequest.StartEvent.\n * Use `create(StreamInputRequest_StartEventSchema)` to create a new message.\n */\nexport const StreamInputRequest_StartEventSchema: GenMessage<StreamInputRequest_StartEvent> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 14, 0)\n\n/**\n * @generated from message process.StreamInputRequest.DataEvent\n */\nexport type StreamInputRequest_DataEvent =\n  Message<'process.StreamInputRequest.DataEvent'> & {\n    /**\n     * @generated from field: process.ProcessInput input = 2;\n     */\n    input?: ProcessInput\n  }\n\n/**\n * Describes the message process.StreamInputRequest.DataEvent.\n * Use `create(StreamInputRequest_DataEventSchema)` to create a new message.\n */\nexport const StreamInputRequest_DataEventSchema: GenMessage<StreamInputRequest_DataEvent> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 14, 1)\n\n/**\n * @generated from message process.StreamInputRequest.KeepAlive\n */\nexport type StreamInputRequest_KeepAlive =\n  Message<'process.StreamInputRequest.KeepAlive'> & {}\n\n/**\n * Describes the message process.StreamInputRequest.KeepAlive.\n * Use `create(StreamInputRequest_KeepAliveSchema)` to create a new message.\n */\nexport const StreamInputRequest_KeepAliveSchema: GenMessage<StreamInputRequest_KeepAlive> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 14, 2)\n\n/**\n * @generated from message process.StreamInputResponse\n */\nexport type StreamInputResponse = Message<'process.StreamInputResponse'> & {}\n\n/**\n * Describes the message process.StreamInputResponse.\n * Use `create(StreamInputResponseSchema)` to create a new message.\n */\nexport const StreamInputResponseSchema: GenMessage<StreamInputResponse> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 15)\n\n/**\n * @generated from message process.SendSignalRequest\n */\nexport type SendSignalRequest = Message<'process.SendSignalRequest'> & {\n  /**\n   * @generated from field: process.ProcessSelector process = 1;\n   */\n  process?: ProcessSelector\n\n  /**\n   * @generated from field: process.Signal signal = 2;\n   */\n  signal: Signal\n}\n\n/**\n * Describes the message process.SendSignalRequest.\n * Use `create(SendSignalRequestSchema)` to create a new message.\n */\nexport const SendSignalRequestSchema: GenMessage<SendSignalRequest> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 16)\n\n/**\n * @generated from message process.SendSignalResponse\n */\nexport type SendSignalResponse = Message<'process.SendSignalResponse'> & {}\n\n/**\n * Describes the message process.SendSignalResponse.\n * Use `create(SendSignalResponseSchema)` to create a new message.\n */\nexport const SendSignalResponseSchema: GenMessage<SendSignalResponse> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 17)\n\n/**\n * @generated from message process.CloseStdinRequest\n */\nexport type CloseStdinRequest = Message<'process.CloseStdinRequest'> & {\n  /**\n   * @generated from field: process.ProcessSelector process = 1;\n   */\n  process?: ProcessSelector\n}\n\n/**\n * Describes the message process.CloseStdinRequest.\n * Use `create(CloseStdinRequestSchema)` to create a new message.\n */\nexport const CloseStdinRequestSchema: GenMessage<CloseStdinRequest> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 18)\n\n/**\n * @generated from message process.CloseStdinResponse\n */\nexport type CloseStdinResponse = Message<'process.CloseStdinResponse'> & {}\n\n/**\n * Describes the message process.CloseStdinResponse.\n * Use `create(CloseStdinResponseSchema)` to create a new message.\n */\nexport const CloseStdinResponseSchema: GenMessage<CloseStdinResponse> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 19)\n\n/**\n * @generated from message process.ConnectRequest\n */\nexport type ConnectRequest = Message<'process.ConnectRequest'> & {\n  /**\n   * @generated from field: process.ProcessSelector process = 1;\n   */\n  process?: ProcessSelector\n}\n\n/**\n * Describes the message process.ConnectRequest.\n * Use `create(ConnectRequestSchema)` to create a new message.\n */\nexport const ConnectRequestSchema: GenMessage<ConnectRequest> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 20)\n\n/**\n * @generated from message process.ProcessSelector\n */\nexport type ProcessSelector = Message<'process.ProcessSelector'> & {\n  /**\n   * @generated from oneof process.ProcessSelector.selector\n   */\n  selector:\n    | {\n        /**\n         * @generated from field: uint32 pid = 1;\n         */\n        value: number\n        case: 'pid'\n      }\n    | {\n        /**\n         * @generated from field: string tag = 2;\n         */\n        value: string\n        case: 'tag'\n      }\n    | { case: undefined; value?: undefined }\n}\n\n/**\n * Describes the message process.ProcessSelector.\n * Use `create(ProcessSelectorSchema)` to create a new message.\n */\nexport const ProcessSelectorSchema: GenMessage<ProcessSelector> =\n  /*@__PURE__*/\n  messageDesc(file_process_process, 21)\n\n/**\n * @generated from enum process.Signal\n */\nexport enum Signal {\n  /**\n   * @generated from enum value: SIGNAL_UNSPECIFIED = 0;\n   */\n  UNSPECIFIED = 0,\n\n  /**\n   * @generated from enum value: SIGNAL_SIGTERM = 15;\n   */\n  SIGTERM = 15,\n\n  /**\n   * @generated from enum value: SIGNAL_SIGKILL = 9;\n   */\n  SIGKILL = 9,\n}\n\n/**\n * Describes the enum process.Signal.\n */\nexport const SignalSchema: GenEnum<Signal> =\n  /*@__PURE__*/\n  enumDesc(file_process_process, 0)\n\n/**\n * @generated from service process.Process\n */\nexport const Process: GenService<{\n  /**\n   * @generated from rpc process.Process.List\n   */\n  list: {\n    methodKind: 'unary'\n    input: typeof ListRequestSchema\n    output: typeof ListResponseSchema\n  }\n  /**\n   * @generated from rpc process.Process.Connect\n   */\n  connect: {\n    methodKind: 'server_streaming'\n    input: typeof ConnectRequestSchema\n    output: typeof ConnectResponseSchema\n  }\n  /**\n   * @generated from rpc process.Process.Start\n   */\n  start: {\n    methodKind: 'server_streaming'\n    input: typeof StartRequestSchema\n    output: typeof StartResponseSchema\n  }\n  /**\n   * @generated from rpc process.Process.Update\n   */\n  update: {\n    methodKind: 'unary'\n    input: typeof UpdateRequestSchema\n    output: typeof UpdateResponseSchema\n  }\n  /**\n   * Client input stream ensures ordering of messages\n   *\n   * @generated from rpc process.Process.StreamInput\n   */\n  streamInput: {\n    methodKind: 'client_streaming'\n    input: typeof StreamInputRequestSchema\n    output: typeof StreamInputResponseSchema\n  }\n  /**\n   * @generated from rpc process.Process.SendInput\n   */\n  sendInput: {\n    methodKind: 'unary'\n    input: typeof SendInputRequestSchema\n    output: typeof SendInputResponseSchema\n  }\n  /**\n   * @generated from rpc process.Process.SendSignal\n   */\n  sendSignal: {\n    methodKind: 'unary'\n    input: typeof SendSignalRequestSchema\n    output: typeof SendSignalResponseSchema\n  }\n  /**\n   * Close stdin to signal EOF to the process.\n   * Only works for non-PTY processes. For PTY, send Ctrl+D (0x04) instead.\n   *\n   * @generated from rpc process.Process.CloseStdin\n   */\n  closeStdin: {\n    methodKind: 'unary'\n    input: typeof CloseStdinRequestSchema\n    output: typeof CloseStdinResponseSchema\n  }\n}> = /*@__PURE__*/ serviceDesc(file_process_process, 0)\n","import {\n  Code,\n  ConnectError,\n  createClient,\n  Client,\n  Transport,\n} from '@connectrpc/connect'\n\nimport {\n  Signal,\n  Process as ProcessService,\n} from '../../envd/process/process_pb'\nimport {\n  ConnectionConfig,\n  ConnectionOpts,\n  Username,\n  KEEPALIVE_PING_HEADER,\n  KEEPALIVE_PING_INTERVAL_SEC,\n  setupRequestController,\n} from '../../connectionConfig'\nimport { CommandHandle } from './commandHandle'\nimport { authenticationHeader, handleRpcError } from '../../envd/rpc'\nimport { handleProcessStartEvent } from '../../envd/api'\n\nexport interface PtyCreateOpts\n  extends Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'> {\n  /**\n   * Number of columns for the PTY.\n   */\n  cols: number\n  /**\n   * Number of rows for the PTY.\n   */\n  rows: number\n  /**\n   * Callback to handle PTY data.\n   */\n  onData: (data: Uint8Array) => void | Promise<void>\n  /**\n   * Timeout for the PTY in **milliseconds**.\n   *\n   * @default 60_000 // 60 seconds\n   */\n  timeoutMs?: number\n  /**\n   * User to use for the PTY.\n   *\n   * @default `default Sandbox user (as specified in the template)`\n   */\n  user?: Username\n  /**\n   * Environment variables for the PTY.\n   *\n   * @default {}\n   */\n  envs?: Record<string, string>\n  /**\n   * Working directory for the PTY.\n   *\n   * @default // home directory of the user used to start the PTY\n   */\n  cwd?: string\n}\n\n/**\n * Options for connecting to a command.\n */\nexport type PtyConnectOpts = Pick<PtyCreateOpts, 'onData' | 'timeoutMs'> &\n  Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>\n\n/**\n * Module for interacting with PTYs (pseudo-terminals) in the sandbox.\n */\nexport class Pty {\n  private readonly rpc: Client<typeof ProcessService>\n  private readonly envdVersion: string\n\n  private readonly defaultPtyConnectionTimeout = 60_000 // 60 seconds\n\n  constructor(\n    private readonly transport: Transport,\n    private readonly connectionConfig: ConnectionConfig,\n    metadata: {\n      version: string\n    }\n  ) {\n    this.rpc = createClient(ProcessService, this.transport)\n    this.envdVersion = metadata.version\n  }\n\n  /**\n   * Create a new PTY (pseudo-terminal).\n   *\n   * @param opts options for creating the PTY.\n   *\n   * @returns handle to interact with the PTY.\n   */\n  async create(opts: PtyCreateOpts) {\n    const requestTimeoutMs =\n      opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n    const envs = opts?.envs ?? {}\n    envs.TERM = envs.TERM ?? 'xterm-256color'\n    envs.LANG = envs.LANG ?? 'C.UTF-8'\n    envs.LC_ALL = envs.LC_ALL ?? 'C.UTF-8'\n\n    const { controller, clearStartTimeout, cleanup } = setupRequestController(\n      requestTimeoutMs,\n      opts?.signal\n    )\n\n    const events = this.rpc.start(\n      {\n        process: {\n          cmd: '/bin/bash',\n          args: ['-i', '-l'],\n          envs: envs,\n          cwd: opts?.cwd,\n        },\n        pty: {\n          size: {\n            cols: opts.cols,\n            rows: opts.rows,\n          },\n        },\n      },\n      {\n        headers: {\n          ...authenticationHeader(this.envdVersion, opts?.user),\n          [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),\n        },\n        signal: controller.signal,\n        timeoutMs: opts?.timeoutMs ?? this.defaultPtyConnectionTimeout,\n      }\n    )\n\n    try {\n      const pid = await handleProcessStartEvent(events)\n      clearStartTimeout()\n\n      return new CommandHandle(\n        pid,\n        cleanup,\n        () => this.kill(pid),\n        events,\n        undefined,\n        undefined,\n        opts.onData\n      )\n    } catch (err) {\n      cleanup()\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * Connect to a running PTY.\n   *\n   * @param pid process ID of the PTY to connect to. You can get the list of running PTYs using {@link Commands.list}.\n   * @param opts connection options.\n   *\n   * @returns handle to interact with the PTY.\n   */\n  async connect(pid: number, opts?: PtyConnectOpts): Promise<CommandHandle> {\n    const requestTimeoutMs =\n      opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n    const { controller, clearStartTimeout, cleanup } = setupRequestController(\n      requestTimeoutMs,\n      opts?.signal\n    )\n\n    const events = this.rpc.connect(\n      {\n        process: {\n          selector: {\n            case: 'pid',\n            value: pid,\n          },\n        },\n      },\n      {\n        signal: controller.signal,\n        headers: {\n          [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),\n        },\n        timeoutMs: opts?.timeoutMs ?? this.defaultPtyConnectionTimeout,\n      }\n    )\n\n    try {\n      const pid = await handleProcessStartEvent(events)\n      clearStartTimeout()\n\n      return new CommandHandle(\n        pid,\n        cleanup,\n        () => this.kill(pid),\n        events,\n        undefined,\n        undefined,\n        opts?.onData\n      )\n    } catch (err) {\n      cleanup()\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * Send input to a PTY.\n   *\n   * @param pid process ID of the PTY.\n   * @param data input data to send to the PTY.\n   * @param opts connection options.\n   */\n  async sendInput(\n    pid: number,\n    data: Uint8Array,\n    opts?: Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>\n  ): Promise<void> {\n    try {\n      await this.rpc.sendInput(\n        {\n          input: {\n            input: {\n              case: 'pty',\n              value: data,\n            },\n          },\n          process: {\n            selector: {\n              case: 'pid',\n              value: pid,\n            },\n          },\n        },\n        {\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n    } catch (err) {\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * Resize PTY.\n   * Call this when the terminal window is resized and the number of columns and rows has changed.\n   *\n   * @param pid process ID of the PTY.\n   * @param size new size of the PTY.\n   * @param opts connection options.\n   */\n  async resize(\n    pid: number,\n    size: {\n      cols: number\n      rows: number\n    },\n    opts?: Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>\n  ): Promise<void> {\n    try {\n      await this.rpc.update(\n        {\n          process: {\n            selector: {\n              case: 'pid',\n              value: pid,\n            },\n          },\n          pty: {\n            size,\n          },\n        },\n        {\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n    } catch (err) {\n      throw handleRpcError(err)\n    }\n  }\n\n  /**\n   * Kill a running PTY specified by process ID.\n   * It uses `SIGKILL` signal to kill the PTY.\n   *\n   * @param pid process ID of the PTY.\n   * @param opts connection options.\n   *\n   * @returns `true` if the PTY was killed, `false` if the PTY was not found.\n   */\n  async kill(\n    pid: number,\n    opts?: Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>\n  ): Promise<boolean> {\n    try {\n      await this.rpc.sendSignal(\n        {\n          process: {\n            selector: {\n              case: 'pid',\n              value: pid,\n            },\n          },\n          signal: Signal.SIGKILL,\n        },\n        {\n          signal: this.connectionConfig.getSignal(\n            opts?.requestTimeoutMs,\n            opts?.signal\n          ),\n        }\n      )\n\n      return true\n    } catch (err) {\n      if (err instanceof ConnectError) {\n        if (err.code === Code.NotFound) {\n          return false\n        }\n      }\n\n      throw handleRpcError(err)\n    }\n  }\n}\n","import { ApiClient, components, handleApiError } from '../api'\nimport {\n  ConnectionConfig,\n  ConnectionOpts,\n  DEFAULT_SANDBOX_TIMEOUT_MS,\n} from '../connectionConfig'\nimport { compareVersions } from 'compare-versions'\nimport {\n  InvalidArgumentError,\n  SandboxNotFoundError,\n  TemplateError,\n} from '../errors'\nimport { timeoutToSeconds } from '../utils'\nimport type { Volume } from '../volume'\nimport type { McpServer as BaseMcpServer } from './mcp'\n\n/**\n * Extended MCP server configuration that includes base servers\n * and allows dynamic GitHub-based MCP servers with custom run and install commands.\n */\nexport type McpServer = BaseMcpServer | GitHubMcpServer\n\nexport type GitHubMcpServer = {\n  [key: `github/${string}`]: {\n    /**\n     * Command to run the MCP server. Must start a stdio-compatible server.\n     */\n    runCmd: string\n    /**\n     * Command to install dependencies for the MCP server. Working directory is the root of the github repository.\n     */\n    installCmd?: string\n    /**\n     * Environment variables to set in the MCP process.\n     */\n    envs?: Record<string, string>\n  }\n}\n\nexport type SandboxNetworkOpts = {\n  /**\n   * Allow outbound traffic from the sandbox to the specified addresses.\n   * If `allowOut` is not specified, all outbound traffic is allowed.\n   *\n   * Examples:\n   * - To allow traffic to a specific addresses: `[\"1.1.1.1\", \"8.8.8.0/24\"]`\n   */\n  allowOut?: string[]\n\n  /**\n   * Deny outbound traffic from the sandbox to the specified addresses.\n   *\n   * Examples:\n   * - To deny traffic to a specific addresses: `[\"1.1.1.1\", \"8.8.8.0/24\"]`\n   */\n  denyOut?: string[]\n\n  /**\n   * Specify if the sandbox URLs should be accessible only with authentication.\n   * @default true\n   */\n  allowPublicTraffic?: boolean\n\n  /** Specify host mask which will be used for all sandbox requests in the header.\n   * You can use the ${PORT} variable that will be replaced with the actual port number of the service.\n   *\n   * @default ${PORT}-sandboxid.e2b.app\n   */\n  maskRequestHost?: string\n}\n\nexport type SandboxLifecycle = {\n  /**\n   * Action to take when sandbox timeout is reached.\n   * @default \"kill\"\n   */\n  onTimeout: 'pause' | 'kill'\n\n  /**\n   * Auto-resume enabled flag.\n   * @default false\n   * Can be `true` only when `onTimeout` is `pause`.\n   */\n  autoResume?: boolean\n}\n\nexport type SandboxInfoLifecycle = {\n  /**\n   * Action to take when sandbox timeout is reached.\n   */\n  onTimeout: 'pause' | 'kill'\n\n  /**\n   * Whether the sandbox can auto-resume.\n   */\n  autoResume: boolean\n}\n\n/**\n * Options for request to the Sandbox API.\n */\nexport interface SandboxApiOpts\n  extends Partial<\n    Pick<\n      ConnectionOpts,\n      'apiKey' | 'headers' | 'debug' | 'domain' | 'requestTimeoutMs' | 'signal'\n    >\n  > {}\n\n/**\n * Options for creating a new Sandbox.\n */\nexport interface SandboxOpts extends ConnectionOpts {\n  /**\n   * Sandbox template name or ID.\n   *\n   * @default 'base' (or 'mcp-gateway' when `mcp` option is set)\n   */\n  template?: string\n\n  /**\n   * Custom metadata for the sandbox.\n   *\n   * @default {}\n   */\n  metadata?: Record<string, string>\n\n  /**\n   * Custom environment variables for the sandbox.\n   *\n   * Used when executing commands and code in the sandbox.\n   * Can be overridden with the `envs` argument when executing commands or code.\n   *\n   * @default {}\n   */\n  envs?: Record<string, string>\n\n  /**\n   * Timeout for the sandbox in **milliseconds**.\n   * Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users.\n   *\n   * @default 300_000 // 5 minutes\n   */\n  timeoutMs?: number\n\n  /**\n   * Secure all traffic coming to the sandbox controller with auth token\n   *\n   * @default true\n   */\n  secure?: boolean\n\n  /**\n   * Allow sandbox to access the internet. If set to `False`, it works the same as setting network `denyOut` to `[0.0.0.0/0]`.\n   *\n   * @default true\n   */\n  allowInternetAccess?: boolean\n\n  /**\n   * MCP server to enable in the sandbox\n   * @default undefined\n   */\n  mcp?: McpServer\n\n  /**\n   * Sandbox network configuration\n   */\n  network?: SandboxNetworkOpts\n\n  /**\n   * Volume mounts for the sandbox.\n   *\n   * The keys are mount paths inside the sandbox and the values are either\n   * a `Volume` instance or a string representing the volume name.\n   *\n   * @default undefined\n   */\n  volumeMounts?: Record<string, Volume | string>\n\n  /**\n   * Sandbox URL. Used for local development\n   */\n  sandboxUrl?: string\n\n  /**\n   * Sandbox lifecycle configuration.\n   */\n  lifecycle?: SandboxLifecycle\n}\n\n/**\n * Options for connecting to a Sandbox.\n */\nexport type SandboxConnectOpts = ConnectionOpts & {\n  /**\n   * Timeout for the sandbox in **milliseconds**.\n   * For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.\n   * Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users.\n   *\n   * @default 300_000 // 5 minutes\n   */\n  timeoutMs?: number\n}\n\n/**\n * State of the sandbox.\n */\nexport type SandboxState = 'running' | 'paused'\n\nexport interface SandboxListOpts extends Omit<SandboxApiOpts, 'signal'> {\n  /**\n   * Filter the list of sandboxes, e.g. by metadata `metadata:{\"key\": \"value\"}`, if there are multiple filters they are combined with AND.\n   *\n   */\n  query?: {\n    metadata?: Record<string, string>\n    /**\n     * Filter the list of sandboxes by state.\n     * @default ['running', 'paused']\n     */\n    state?: Array<SandboxState>\n  }\n\n  /**\n   * Number of sandboxes to return per page.\n   *\n   * @default 100\n   */\n  limit?: number\n\n  /**\n   * Token to the next page.\n   */\n  nextToken?: string\n}\n\nexport interface SandboxMetricsOpts extends SandboxApiOpts {\n  /**\n   * Start time for the metrics, defaults to the start of the sandbox\n   */\n  start?: Date\n  /**\n   * End time for the metrics, defaults to the current time\n   */\n  end?: Date\n}\n\n/**\n * Options for listing snapshots.\n */\nexport interface SnapshotListOpts extends Omit<SandboxApiOpts, 'signal'> {\n  /**\n   * Filter snapshots by source sandbox ID.\n   */\n  sandboxId?: string\n\n  /**\n   * Number of snapshots to return per page.\n   *\n   * @default 100\n   */\n  limit?: number\n\n  /**\n   * Token to the next page.\n   */\n  nextToken?: string\n}\n\n/**\n * Information about a snapshot.\n */\nexport interface SnapshotInfo {\n  /**\n   * Snapshot identifier — template ID with tag, or namespaced name with tag (e.g. my-snapshot:latest).\n   * Can be used with Sandbox.create() to create a new sandbox from this snapshot.\n   */\n  snapshotId: string\n\n  /**\n   * Full names of the snapshot template including team namespace and tag (e.g. team-slug/my-snapshot:v2).\n   */\n  names: string[]\n}\n\n/**\n * Options for creating a snapshot.\n */\nexport interface CreateSnapshotOpts extends SandboxApiOpts {\n  /**\n   * Optional name for the snapshot template.\n   * If a snapshot template with this name already exists, a new build will be assigned\n   * to the existing template instead of creating a new one.\n   */\n  name?: string\n}\n\n/**\n * Information about a sandbox.\n */\nexport interface SandboxInfo {\n  /**\n   * Sandbox ID.\n   */\n  sandboxId: string\n\n  /**\n   * Template ID.\n   */\n  templateId: string\n\n  /**\n   * Template name.\n   */\n  name?: string\n\n  /**\n   * Saved sandbox metadata.\n   */\n  metadata: Record<string, string>\n\n  /**\n   * Sandbox start time.\n   */\n  startedAt: Date\n\n  /**\n   * Sandbox expiration date.\n   */\n  endAt: Date\n\n  /**\n   * Sandbox state.\n   *\n   * @string can be `running` or `paused`\n   */\n  state: SandboxState\n\n  /**\n   * Sandbox CPU count.\n   */\n  cpuCount: number\n\n  /**\n   * Sandbox Memory size in MiB.\n   */\n  memoryMB: number\n\n  /**\n   * Envd version.\n   */\n  envdVersion: string\n\n  /**\n   * Whether internet access was explicitly enabled or disabled for the sandbox.\n   */\n  allowInternetAccess?: boolean | undefined\n\n  /**\n   * Sandbox network configuration.\n   */\n  network?: SandboxNetworkOpts\n\n  /**\n   * Sandbox lifecycle configuration.\n   */\n  lifecycle?: SandboxInfoLifecycle\n\n  /**\n   * Volume mounts for the sandbox.\n   */\n  volumeMounts?: Array<{ name: string; path: string }>\n}\n\n/**\n * Sandbox resource usage metrics.\n */\nexport interface SandboxMetrics {\n  /**\n   * Timestamp of the metrics.\n   */\n  timestamp: Date\n\n  /**\n   * CPU usage in percentage.\n   */\n  cpuUsedPct: number\n\n  /**\n   * Number of CPU cores.\n   */\n  cpuCount: number\n\n  /**\n   * Memory usage in bytes.\n   */\n  memUsed: number\n\n  /**\n   * Total memory available in bytes.\n   */\n  memTotal: number\n\n  /**\n   * Used disk space in bytes.\n   */\n  diskUsed: number\n\n  /**\n   * Total disk space available in bytes.\n   */\n  diskTotal: number\n}\n\nexport class SandboxApi {\n  protected constructor() {}\n\n  /**\n   * Kill the sandbox specified by sandbox ID.\n   *\n   * @param sandboxId sandbox ID.\n   * @param opts connection options.\n   *\n   * @returns `true` if the sandbox was found and killed, `false` otherwise.\n   */\n  static async kill(\n    sandboxId: string,\n    opts?: SandboxApiOpts\n  ): Promise<boolean> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.DELETE('/sandboxes/{sandboxID}', {\n      params: {\n        path: {\n          sandboxID: sandboxId,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.error?.code === 404) {\n      return false\n    }\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    return true\n  }\n\n  /**\n   * Get sandbox information like sandbox ID, template, metadata, started at/end at date.\n   *\n   * @param sandboxId sandbox ID.\n   * @param opts connection options.\n   *\n   * @returns sandbox information.\n   */\n  static async getInfo(\n    sandboxId: string,\n    opts?: SandboxApiOpts\n  ): Promise<SandboxInfo> {\n    const fullInfo = await this.getFullInfo(sandboxId, opts)\n    delete fullInfo.envdAccessToken\n    delete fullInfo.sandboxDomain\n\n    return fullInfo\n  }\n\n  /**\n   * Get the metrics of the sandbox.\n   *\n   * @param sandboxId sandbox ID.\n   * @param opts sandbox metrics options.\n   *\n   * @returns  List of sandbox metrics containing CPU, memory and disk usage information.\n   */\n  static async getMetrics(\n    sandboxId: string,\n    opts?: SandboxMetricsOpts\n  ): Promise<SandboxMetrics[]> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    // JS timestamp is in milliseconds, convert to unix (seconds)\n    const start = opts?.start\n      ? Math.round(opts.start.getTime() / 1000)\n      : undefined\n    const end = opts?.end ? Math.round(opts.end.getTime() / 1000) : undefined\n    const res = await client.api.GET('/sandboxes/{sandboxID}/metrics', {\n      params: {\n        path: {\n          sandboxID: sandboxId,\n          start,\n          end,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    return (\n      res.data?.map((metric: components['schemas']['SandboxMetric']) => ({\n        timestamp: new Date(metric.timestamp),\n        cpuUsedPct: metric.cpuUsedPct,\n        cpuCount: metric.cpuCount,\n        memUsed: metric.memUsed,\n        memTotal: metric.memTotal,\n        diskUsed: metric.diskUsed,\n        diskTotal: metric.diskTotal,\n      })) ?? []\n    )\n  }\n\n  /**\n   * Set the timeout of the specified sandbox.\n   * After the timeout expires the sandbox will be automatically killed.\n   *\n   * This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to {@link Sandbox.setTimeout}.\n   *\n   * Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users.\n   *\n   * @param sandboxId sandbox ID.\n   * @param timeoutMs timeout in **milliseconds**.\n   * @param opts connection options.\n   */\n  static async setTimeout(\n    sandboxId: string,\n    timeoutMs: number,\n    opts?: SandboxApiOpts\n  ): Promise<void> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.POST('/sandboxes/{sandboxID}/timeout', {\n      params: {\n        path: {\n          sandboxID: sandboxId,\n        },\n      },\n      body: {\n        timeout: timeoutToSeconds(timeoutMs),\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.error?.code === 404) {\n      throw new SandboxNotFoundError(`Sandbox ${sandboxId} not found`)\n    }\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n  }\n\n  static async getFullInfo(sandboxId: string, opts?: SandboxApiOpts) {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.GET('/sandboxes/{sandboxID}', {\n      params: {\n        path: {\n          sandboxID: sandboxId,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.error?.code === 404) {\n      throw new SandboxNotFoundError(`Sandbox ${sandboxId} not found`)\n    }\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    if (!res.data) {\n      throw new Error('Sandbox not found')\n    }\n\n    return {\n      sandboxId: res.data.sandboxID,\n      templateId: res.data.templateID,\n      ...(res.data.alias && { name: res.data.alias }),\n      metadata: res.data.metadata ?? {},\n      allowInternetAccess: res.data.allowInternetAccess ?? undefined,\n      envdVersion: res.data.envdVersion,\n      envdAccessToken: res.data.envdAccessToken,\n      startedAt: new Date(res.data.startedAt),\n      endAt: new Date(res.data.endAt),\n      state: res.data.state,\n      cpuCount: res.data.cpuCount,\n      memoryMB: res.data.memoryMB,\n      network: res.data.network\n        ? {\n            allowOut: res.data.network.allowOut,\n            denyOut: res.data.network.denyOut,\n            allowPublicTraffic: res.data.network.allowPublicTraffic,\n            maskRequestHost: res.data.network.maskRequestHost,\n          }\n        : undefined,\n      lifecycle: res.data.lifecycle\n        ? {\n            onTimeout: res.data.lifecycle.onTimeout,\n            autoResume: res.data.lifecycle.autoResume,\n          }\n        : undefined,\n      sandboxDomain: res.data.domain || undefined,\n      volumeMounts: res.data.volumeMounts ?? [],\n    }\n  }\n\n  /**\n   * Pause the sandbox specified by sandbox ID.\n   *\n   * @param sandboxId sandbox ID.\n   * @param opts connection options.\n   *\n   * @returns `true` if the sandbox got paused, `false` if the sandbox was already paused.\n   */\n  static async pause(\n    sandboxId: string,\n    opts?: SandboxApiOpts\n  ): Promise<boolean> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.POST('/sandboxes/{sandboxID}/pause', {\n      params: {\n        path: {\n          sandboxID: sandboxId,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.error?.code === 404) {\n      throw new SandboxNotFoundError(`Sandbox ${sandboxId} not found`)\n    }\n\n    if (res.error?.code === 409) {\n      // Sandbox is already paused\n      return false\n    }\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    return true\n  }\n\n  /**\n   * @deprecated Use {@link SandboxApi.pause} instead.\n   */\n  static async betaPause(\n    sandboxId: string,\n    opts?: SandboxApiOpts\n  ): Promise<boolean> {\n    return this.pause(sandboxId, opts)\n  }\n\n  /**\n   * Create a snapshot from a sandbox.\n   *\n   * The sandbox will be paused while the snapshot is being created.\n   * The snapshot can be used to create new sandboxes with the same state.\n   * The snapshot is a persistent image that survives sandbox deletion.\n   *\n   * @param sandboxId sandbox ID to create snapshot from.\n   * @param opts snapshot creation options including optional name and connection options.\n   *\n   * @returns snapshot information including the snapshot name that can be used with Sandbox.create().\n   */\n  static async createSnapshot(\n    sandboxId: string,\n    opts?: CreateSnapshotOpts\n  ): Promise<SnapshotInfo> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.POST('/sandboxes/{sandboxID}/snapshots', {\n      params: {\n        path: {\n          sandboxID: sandboxId,\n        },\n      },\n      body: opts?.name ? { name: opts.name } : {},\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.error?.code === 404) {\n      throw new SandboxNotFoundError(`Sandbox ${sandboxId} not found`)\n    }\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    return {\n      snapshotId: res.data!.snapshotID,\n      names: res.data!.names ?? [],\n    }\n  }\n\n  /**\n   * List all snapshots.\n   *\n   * @param opts list options including filters and pagination.\n   *\n   * @returns paginator for listing snapshots.\n   */\n  static listSnapshots(opts?: SnapshotListOpts): SnapshotPaginator {\n    return new SnapshotPaginator(opts)\n  }\n\n  /**\n   * Delete a snapshot.\n   *\n   * @param snapshotId snapshot ID.\n   * @param opts connection options.\n   *\n   * @returns `true` if the snapshot was deleted, `false` if it was not found.\n   */\n  static async deleteSnapshot(\n    snapshotId: string,\n    opts?: SandboxApiOpts\n  ): Promise<boolean> {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.DELETE('/templates/{templateID}', {\n      params: {\n        path: {\n          templateID: snapshotId,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.error?.code === 404) {\n      return false\n    }\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    return true\n  }\n\n  protected static async createSandbox(\n    template: string,\n    timeoutMs: number,\n    opts?: SandboxOpts\n  ) {\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n    const onTimeout = opts?.lifecycle?.onTimeout ?? 'kill'\n    const autoResume = opts?.lifecycle?.autoResume ?? false\n\n    if (autoResume && onTimeout !== 'pause') {\n      throw new InvalidArgumentError(\n        \"autoResume can only be true when the resolved onTimeout is 'pause'.\"\n      )\n    }\n\n    const body: components['schemas']['NewSandbox'] = {\n      templateID: template,\n      metadata: opts?.metadata,\n      mcp: opts?.mcp as Record<string, unknown> | undefined,\n      envVars: opts?.envs,\n      timeout: timeoutToSeconds(timeoutMs),\n      secure: opts?.secure ?? true,\n      allow_internet_access: opts?.allowInternetAccess ?? true,\n      network: opts?.network,\n      autoPause: onTimeout === 'pause',\n      autoResume: { enabled: autoResume },\n    }\n\n    if (opts?.volumeMounts) {\n      body.volumeMounts = Object.entries(opts.volumeMounts).map(\n        ([mountPath, vol]) => ({\n          name: typeof vol === 'string' ? vol : vol.name,\n          path: mountPath,\n        })\n      )\n    }\n\n    const res = await client.api.POST('/sandboxes', {\n      body,\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    if (compareVersions(res.data!.envdVersion, '0.1.0') < 0) {\n      await this.kill(res.data!.sandboxID, opts)\n      throw new TemplateError(\n        'You need to update the template to use the new SDK. ' +\n          'You can do this by running `e2b template build` in the directory with the template.'\n      )\n    }\n\n    return {\n      sandboxId: res.data!.sandboxID,\n      sandboxDomain: res.data!.domain || undefined,\n      envdVersion: res.data!.envdVersion,\n      envdAccessToken: res.data!.envdAccessToken,\n      trafficAccessToken: res.data!.trafficAccessToken || undefined,\n    }\n  }\n\n  protected static async connectSandbox(\n    sandboxId: string,\n    opts?: SandboxConnectOpts\n  ) {\n    const timeoutMs = opts?.timeoutMs ?? DEFAULT_SANDBOX_TIMEOUT_MS\n\n    const config = new ConnectionConfig(opts)\n    const client = new ApiClient(config)\n\n    const res = await client.api.POST('/sandboxes/{sandboxID}/connect', {\n      params: {\n        path: {\n          sandboxID: sandboxId,\n        },\n      },\n      body: {\n        timeout: timeoutToSeconds(timeoutMs),\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    if (res.error?.code === 404) {\n      throw new SandboxNotFoundError(`Paused sandbox ${sandboxId} not found`)\n    }\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    return {\n      sandboxId: res.data!.sandboxID,\n      sandboxDomain: res.data!.domain || undefined,\n      envdVersion: res.data!.envdVersion,\n      envdAccessToken: res.data!.envdAccessToken,\n      trafficAccessToken: res.data!.trafficAccessToken || undefined,\n    }\n  }\n}\n\nabstract class BasePaginator<T> {\n  protected readonly opts?: SandboxApiOpts\n  protected readonly limit?: number\n\n  private _hasNext: boolean\n  private _nextToken?: string\n\n  constructor(opts?: SandboxApiOpts, limit?: number, nextToken?: string) {\n    this.opts = opts\n    this.limit = limit\n\n    this._hasNext = true\n    this._nextToken = nextToken\n  }\n\n  /**\n   * Returns true if there are more items to fetch.\n   */\n  get hasNext(): boolean {\n    return this._hasNext\n  }\n\n  /**\n   * Returns the next token to use for pagination.\n   */\n  get nextToken(): string | undefined {\n    return this._nextToken\n  }\n\n  protected updatePagination(response: Response) {\n    this._nextToken = response.headers.get('x-next-token') || undefined\n    this._hasNext = !!this._nextToken\n  }\n\n  /**\n   * Get the next page of items.\n   *\n   * @param opts per-call connection options. When provided, this call uses\n   * these options (e.g. `apiKey`, `domain`, `headers`, `requestTimeoutMs`,\n   * `signal`) instead of the ones the paginator was constructed with.\n   * Aborting a page via `signal` does not affect subsequent {@link BasePaginator.nextItems}\n   * calls — pass a fresh signal each call you want to be cancellable.\n   *\n   * @throws Error if there are no more items to fetch. Call this method only if `hasNext` is `true`.\n   *\n   * @returns List of items\n   */\n  abstract nextItems(opts?: SandboxApiOpts): Promise<T[]>\n}\n\n/**\n * Paginator for listing sandboxes.\n *\n * @example\n * ```ts\n * const paginator = Sandbox.list()\n * while (paginator.hasNext) {\n *   const sandboxes = await paginator.nextItems()\n *   console.log(sandboxes)\n * }\n * ```\n */\nexport class SandboxPaginator extends BasePaginator<SandboxInfo> {\n  private query: SandboxListOpts['query']\n\n  constructor(opts?: SandboxListOpts) {\n    super(opts, opts?.limit, opts?.nextToken)\n\n    this.query = opts?.query\n  }\n\n  async nextItems(opts?: SandboxApiOpts): Promise<SandboxInfo[]> {\n    if (!this.hasNext) {\n      throw new Error('No more items to fetch')\n    }\n\n    let metadata = undefined\n    if (this.query?.metadata) {\n      const encodedPairs: Record<string, string> = Object.fromEntries(\n        Object.entries(this.query.metadata).map(([key, value]) => [\n          encodeURIComponent(key),\n          encodeURIComponent(value),\n        ])\n      )\n\n      metadata = new URLSearchParams(encodedPairs).toString()\n    }\n\n    const config = new ConnectionConfig({ ...this.opts, ...opts })\n    const client = new ApiClient(config)\n\n    const res = await client.api.GET('/v2/sandboxes', {\n      params: {\n        query: {\n          metadata,\n          state: this.query?.state,\n          limit: this.limit,\n          nextToken: this.nextToken,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    this.updatePagination(res.response)\n\n    return (res.data ?? []).map(\n      (sandbox: components['schemas']['ListedSandbox']) => ({\n        sandboxId: sandbox.sandboxID,\n        templateId: sandbox.templateID,\n        ...(sandbox.alias && { name: sandbox.alias }),\n        metadata: sandbox.metadata ?? {},\n        startedAt: new Date(sandbox.startedAt),\n        endAt: new Date(sandbox.endAt),\n        state: sandbox.state,\n        cpuCount: sandbox.cpuCount,\n        memoryMB: sandbox.memoryMB,\n        envdVersion: sandbox.envdVersion,\n        volumeMounts: sandbox.volumeMounts ?? [],\n      })\n    )\n  }\n}\n\n/**\n * Paginator for listing snapshots.\n *\n * @example\n * ```ts\n * const paginator = Sandbox.listSnapshots()\n * while (paginator.hasNext) {\n *   const snapshots = await paginator.nextItems()\n *   console.log(snapshots)\n * }\n * ```\n */\nexport class SnapshotPaginator extends BasePaginator<SnapshotInfo> {\n  private readonly sandboxId?: string\n\n  constructor(opts?: SnapshotListOpts) {\n    super(opts, opts?.limit, opts?.nextToken)\n\n    this.sandboxId = opts?.sandboxId\n  }\n\n  async nextItems(opts?: SandboxApiOpts): Promise<SnapshotInfo[]> {\n    if (!this.hasNext) {\n      throw new Error('No more items to fetch')\n    }\n\n    const config = new ConnectionConfig({ ...this.opts, ...opts })\n    const client = new ApiClient(config)\n\n    const res = await client.api.GET('/snapshots', {\n      params: {\n        query: {\n          sandboxID: this.sandboxId,\n          limit: this.limit,\n          nextToken: this.nextToken,\n        },\n      },\n      signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),\n    })\n\n    const err = handleApiError(res)\n    if (err) {\n      throw err\n    }\n\n    this.updatePagination(res.response)\n\n    return (res.data ?? []).map(\n      (snapshot: components['schemas']['SnapshotInfo']) => ({\n        snapshotId: snapshot.snapshotID,\n        names: snapshot.names ?? [],\n      })\n    )\n  }\n}\n","import chalk from 'chalk'\nimport { stripAnsi } from '../utils'\n\n/**\n * Log entry severity levels.\n */\nexport type LogEntryLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/**\n * Represents a single log entry from the template build process.\n */\nexport class LogEntry {\n  constructor(\n    public readonly timestamp: Date,\n    public readonly level: LogEntryLevel,\n    public readonly message: string\n  ) {}\n\n  toString() {\n    return `[${this.timestamp.toISOString()}] [${this.level}] ${stripAnsi(\n      this.message\n    )}`\n  }\n}\n\n/**\n * Special log entry indicating the start of a build process.\n */\nexport class LogEntryStart extends LogEntry {\n  constructor(timestamp: Date, message: string) {\n    super(timestamp, 'debug', message)\n  }\n}\n\n/**\n * Special log entry indicating the end of a build process.\n */\nexport class LogEntryEnd extends LogEntry {\n  constructor(timestamp: Date, message: string) {\n    super(timestamp, 'debug', message)\n  }\n}\n\n/**\n * Interval in milliseconds for updating the build timer display.\n * @internal\n */\nconst TIMER_UPDATE_INTERVAL_MS = 150\n\n/**\n * Default minimum log level to display.\n * @internal\n */\nconst DEFAULT_LEVEL: LogEntryLevel = 'info'\n\n/**\n * Colored labels for each log level.\n * @internal\n */\nconst levels: Record<LogEntryLevel, string> = {\n  error: chalk.red('ERROR'),\n  warn: chalk.hex('#FF4400')('WARN '),\n  info: chalk.hex('#FF8800')('INFO '),\n  debug: chalk.gray('DEBUG'),\n}\n\n/**\n * Numeric ordering of log levels for comparison (lower = less severe).\n * @internal\n */\nconst level_order: Record<LogEntryLevel, number> = {\n  debug: 0,\n  info: 1,\n  warn: 2,\n  error: 3,\n}\n\ninterface DefaultBuildLoggerState {\n  startTime: number\n  animationFrame: number\n  timerInterval: NodeJS.Timeout | undefined\n}\n\nclass DefaultBuildLogger {\n  private minLevel: LogEntryLevel\n  private state: DefaultBuildLoggerState\n\n  constructor(minLevel?: LogEntryLevel) {\n    this.minLevel = minLevel ?? DEFAULT_LEVEL\n    this.state = this.getInitialState()\n  }\n\n  logger(logEntry: LogEntry) {\n    if (logEntry instanceof LogEntryStart) {\n      this.startTimer()\n      return\n    }\n\n    if (logEntry instanceof LogEntryEnd) {\n      clearInterval(this.state.timerInterval)\n      return\n    }\n\n    // Filter by minimum level\n    if (level_order[logEntry.level] < level_order[this.minLevel]) {\n      return\n    }\n\n    const formattedLine = this.formatLogLine(logEntry)\n    process.stdout.write(`${formattedLine}\\n`)\n\n    // Redraw the timer line\n    this.updateTimer()\n  }\n\n  private getInitialState(\n    timerInterval?: NodeJS.Timeout\n  ): DefaultBuildLoggerState {\n    return {\n      startTime: Date.now(),\n      animationFrame: 0,\n      timerInterval: timerInterval,\n    }\n  }\n\n  private formatTimerLine() {\n    const elapsedSeconds = ((Date.now() - this.state.startTime) / 1000).toFixed(\n      1\n    )\n    return `${elapsedSeconds}s`\n  }\n\n  private animateStatus() {\n    const frames = ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']\n    const idx = this.state.animationFrame % frames.length\n    return `${frames[idx]}`\n  }\n\n  private formatLogLine(line: LogEntry) {\n    const timer = this.formatTimerLine().padEnd(5)\n\n    const timestamp = chalk.dim(\n      line.timestamp.toLocaleTimeString(undefined, {\n        hour: '2-digit',\n        minute: '2-digit',\n        second: '2-digit',\n      })\n    )\n\n    const level = levels[line.level] || levels[DEFAULT_LEVEL]\n\n    const msg = line.message\n\n    return `${timer} | ${timestamp} ${level} ${msg}`\n  }\n\n  private startTimer() {\n    if (!process.stdout.isTTY) {\n      return\n    }\n\n    // Start the timer interval\n    const timerInterval = setInterval(\n      this.updateTimer.bind(this),\n      TIMER_UPDATE_INTERVAL_MS\n    )\n\n    this.state = this.getInitialState(timerInterval)\n\n    // Initial timer display\n    this.updateTimer()\n  }\n\n  private updateTimer() {\n    if (!process.stdout.isTTY) {\n      return\n    }\n\n    this.state.animationFrame++\n    const jumpingSquares = this.animateStatus()\n    process.stdout.write(\n      `${jumpingSquares} Building ${this.formatTimerLine()}\\r`\n    )\n  }\n}\n\n/**\n * Create a default build logger with animated timer display.\n *\n * @param options Logger configuration options\n * @param options.minLevel Minimum log level to display (default: 'info')\n * @returns Logger function that accepts LogEntry instances\n *\n * @example\n * ```ts\n * import { Template, defaultBuildLogger } from 'e2b'\n *\n * const template = Template().fromPythonImage()\n *\n * await Template.build(template, {\n *   alias: 'my-template',\n *   onBuildLogs: defaultBuildLogger({ minLevel: 'debug' })\n * })\n * ```\n */\nexport function defaultBuildLogger(options?: {\n  minLevel?: LogEntryLevel\n}): (logEntry: LogEntry) => void {\n  const buildLogger = new DefaultBuildLogger(options?.minLevel)\n\n  return buildLogger.logger.bind(buildLogger)\n}\n","import crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { dynamicImport, dynamicRequire } from '../utils'\nimport { TemplateError } from '../errors'\nimport { BASE_STEP_NAME, FINALIZE_STEP_NAME } from './consts'\nimport type { Path } from 'glob'\nimport type { BuildOptions } from './types'\n\n/**\n * Validate that a source path for copy operations is a relative path that stays\n * within the context directory. This prevents path traversal attacks and ensures\n * files are copied from within the expected directory.\n *\n * @param src The source path to validate\n * @param stackTrace Optional stack trace for error reporting\n * @throws TemplateError if the path is absolute or escapes the context directory\n *\n * Invalid paths:\n * - Absolute paths: /absolute/path, C:\\Windows\\path\n * - Parent directory escapes: ../foo, foo/../../bar, ./foo/../../../bar\n *\n * Valid paths:\n * - Simple relative: foo, foo/bar\n * - Current directory prefix: ./foo, ./foo/bar\n * - Internal parent refs that don't escape: foo/../bar (stays within context)\n */\nexport function validateRelativePath(\n  src: string,\n  stackTrace: string | undefined\n): void {\n  // Check for absolute paths using Node's cross-platform implementation\n  if (path.isAbsolute(src)) {\n    const error = new TemplateError(\n      `Invalid source path \"${src}\": absolute paths are not allowed. Use a relative path within the context directory.`,\n      stackTrace\n    )\n    throw error\n  }\n\n  // Normalize the path and check if it escapes the context directory\n  const normalized = path.normalize(src)\n\n  // After normalization, a path that escapes would be '..' or start with '../'\n  // We check for '..' followed by path separator to avoid false positives on filenames like '..myconfig'\n  // Examples:\n  // - '../foo' -> '../foo' (escapes)\n  // - 'foo/../../bar' -> '../bar' (escapes)\n  // - './foo/../../../bar' -> '../../bar' (escapes)\n  // - 'foo/../bar' -> 'bar' (doesn't escape)\n  // - './foo/bar' -> 'foo/bar' (doesn't escape)\n  // - '..myconfig' -> '..myconfig' (valid filename, doesn't escape)\n  const escapes = normalized === '..' || normalized.startsWith('..' + path.sep)\n\n  if (escapes) {\n    const error = new TemplateError(\n      `Invalid source path \"${src}\": path escapes the context directory. The path must stay within the context directory.`,\n      stackTrace\n    )\n    throw error\n  }\n}\n\n/**\n * Normalize build arguments from different overload signatures.\n * Handles string name or legacy options object with alias.\n *\n * @param nameOrOptions Name or legacy options with alias\n * @param options Optional build options (when first arg is name)\n * @returns Object with normalized name, tags, and build options\n * @throws TemplateError if no template name is provided\n */\nexport function normalizeBuildArguments(\n  nameOrOptions: string | BuildOptions,\n  options?: Omit<BuildOptions, 'alias'>\n): {\n  name: string\n  buildOptions: Omit<BuildOptions, 'alias'>\n} {\n  let name: string\n  let buildOptions: Omit<BuildOptions, 'alias'>\n\n  if (typeof nameOrOptions === 'string') {\n    name = nameOrOptions\n    buildOptions = options ?? {}\n  } else {\n    // Legacy: options object with alias\n    const { alias, ...restOpts } = nameOrOptions\n    name = alias\n    buildOptions = restOpts\n  }\n\n  if (!name || name.length === 0) {\n    throw new TemplateError('Name must be provided')\n  }\n\n  return { name, buildOptions }\n}\n\n/**\n * Read and parse a .dockerignore file.\n *\n * @param contextPath Directory path containing the .dockerignore file\n * @returns Array of ignore patterns (empty lines and comments are filtered out)\n */\nexport function readDockerignore(contextPath: string): string[] {\n  const dockerignorePath = path.join(contextPath, '.dockerignore')\n  if (!fs.existsSync(dockerignorePath)) {\n    return []\n  }\n\n  const content = fs.readFileSync(dockerignorePath, 'utf-8')\n  return content\n    .split('\\n')\n    .map((line) => line.trim())\n    .filter((line) => line && !line.startsWith('#'))\n}\n\n/**\n * Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows)\n * @param path - The path to normalize\n * @returns The normalized path\n */\nfunction normalizePath(path: string): string {\n  return path.replace(/\\\\/g, '/')\n}\n\n/**\n * Get all files for a given path and ignore patterns.\n *\n * @param src Path to the source directory\n * @param contextPath Base directory for resolving relative paths\n * @param ignorePatterns Ignore patterns\n * @returns Array of files\n */\nexport async function getAllFilesInPath(\n  src: string,\n  contextPath: string,\n  ignorePatterns: string[],\n  includeDirectories: boolean = true\n) {\n  const { glob } = await dynamicImport<typeof import('glob')>('glob')\n  const files = new Map<string, Path>()\n\n  const globFiles = await glob(src, {\n    ignore: ignorePatterns,\n    withFileTypes: true,\n    dot: true,\n    // this is required so that the ignore pattern is relative to the file path\n    cwd: contextPath,\n  })\n\n  for (const file of globFiles) {\n    if (file.isDirectory()) {\n      // For directories, add the directory itself and all files inside it\n      if (includeDirectories) {\n        files.set(file.fullpath(), file)\n      }\n      const dirPattern = normalizePath(\n        // When the matched directory is '.', `file.relative()` can be an empty string.\n        // In that case, we want to match all files under the current directory instead of\n        // creating an absolute glob like '/**/*' which would traverse the entire filesystem.\n        path.join(file.relative() || '.', '**/*')\n      )\n      const dirFiles = await glob(dirPattern, {\n        ignore: ignorePatterns,\n        withFileTypes: true,\n        dot: true,\n        cwd: contextPath,\n      })\n      dirFiles.forEach((f) => files.set(f.fullpath(), f))\n    } else {\n      // For files, just add the file\n      files.set(file.fullpath(), file)\n    }\n  }\n\n  return Array.from(files.values()).sort()\n}\n\n/**\n * Calculate a hash of files being copied to detect changes for cache invalidation.\n * The hash includes file content, metadata (mode, size), and relative paths.\n * Note: uid, gid, and mtime are excluded to ensure stable hashes across environments.\n *\n * @param src Source path pattern for files to copy\n * @param dest Destination path where files will be copied\n * @param contextPath Base directory for resolving relative paths\n * @param ignorePatterns Glob patterns to ignore\n * @param resolveSymlinks Whether to resolve symbolic links when hashing\n * @param stackTrace Optional stack trace for error reporting\n * @returns Hex string hash of all files\n * @throws Error if no files match the source pattern\n */\nexport async function calculateFilesHash(\n  src: string,\n  dest: string,\n  contextPath: string,\n  ignorePatterns: string[],\n  resolveSymlinks: boolean,\n  stackTrace: string | undefined\n): Promise<string> {\n  const srcPath = path.join(contextPath, src)\n  const hash = crypto.createHash('sha256')\n  const content = `COPY ${src} ${dest}`\n\n  hash.update(content)\n\n  const files = await getAllFilesInPath(src, contextPath, ignorePatterns, true)\n\n  if (files.length === 0) {\n    const error = new Error(`No files found in ${srcPath}`)\n    if (stackTrace) {\n      error.stack = stackTrace\n    }\n    throw error\n  }\n\n  // Hash stats - only include stable metadata (mode, size)\n  // Exclude uid, gid, and mtime to ensure consistent hashes across environments\n  const hashStats = (stats: fs.Stats) => {\n    hash.update(stats.mode.toString())\n    hash.update(stats.size.toString())\n  }\n\n  // Process files recursively\n  for (const file of files) {\n    // Add a relative path to hash calculation\n    const relativePath = file.relativePosix()\n    hash.update(relativePath)\n\n    // Add stat information to hash calculation\n    if (file.isSymbolicLink()) {\n      // If the symlink is broken, it will return undefined, otherwise it will return a stats object of the target\n      const stats = fs.statSync(file.fullpath(), { throwIfNoEntry: false })\n      const shouldFollow =\n        resolveSymlinks && (stats?.isFile() || stats?.isDirectory())\n\n      if (!shouldFollow) {\n        const stats = fs.lstatSync(file.fullpath())\n\n        hashStats(stats)\n\n        const content = fs.readlinkSync(file.fullpath())\n        hash.update(content)\n\n        continue\n      }\n    }\n\n    const stats = fs.statSync(file.fullpath())\n    hashStats(stats)\n\n    // Add file content to hash calculation\n    if (stats.isFile()) {\n      const content = fs.readFileSync(file.fullpath())\n      hash.update(new Uint8Array(content))\n    }\n  }\n\n  return hash.digest('hex')\n}\n\n/**\n * Get the caller's stack trace frame at a specific depth.\n *\n * @param depth The depth of the stack trace to retrieve\n *   - Levels: caller (e.g., TemplateBase.fromImage) > original caller (e.g., user's template file)\n * @returns The caller frame as a string, or undefined if not available\n */\nexport function getCallerFrame(depth: number): string | undefined {\n  const stackTrace = new Error().stack\n  if (!stackTrace) {\n    return\n  }\n\n  const lines = stackTrace.split('\\n').slice(1) // Skip the this function (getCallerFrame)\n  if (lines.length < depth + 1) {\n    return\n  }\n\n  return lines.slice(depth).join('\\n')\n}\n\n// adopted from https://github.com/sindresorhus/callsites\nexport function callsites(depth: number): NodeJS.CallSite[] {\n  const _originalPrepareStackTrace = Error.prepareStackTrace\n  try {\n    let result: NodeJS.CallSite[] = []\n    Error.prepareStackTrace = (_, callSites) => {\n      const callSitesWithoutCurrent = callSites.slice(depth)\n      result = callSitesWithoutCurrent\n      return callSitesWithoutCurrent\n    }\n\n    new Error().stack\n    return result\n  } finally {\n    Error.prepareStackTrace = _originalPrepareStackTrace\n  }\n}\n\n/**\n * Get the directory of the caller at a specific stack depth.\n *\n * @param depth The depth of the stack trace\n * @returns The caller's directory path, or undefined if not available\n */\nexport function getCallerDirectory(depth: number): string | undefined {\n  // +1 depth to skip this function (getCallerDirectory)\n  const callSites = callsites(depth + 1)\n  if (callSites.length === 0) {\n    return undefined\n  }\n\n  let fileName = callSites[0].getFileName()\n  if (!fileName) {\n    return undefined\n  }\n\n  // Handle file:// URLs returned by getFileName() in ESM modules\n  if (fileName.startsWith('file:')) {\n    // we use the dynamic import to avoid bundling node:url for browser compatibility\n    // getCallerDirectory method is not called in the browser\n    const { fileURLToPath } =\n      dynamicRequire<typeof import('node:url')>('node:url')\n    fileName = fileURLToPath(fileName)\n  }\n\n  return path.dirname(fileName)\n}\n\n/**\n * Convert a numeric file mode to a zero-padded octal string.\n *\n * @param mode File mode as a number (e.g., 493 for 0o755)\n * @returns Zero-padded 4-digit octal string (e.g., \"0755\")\n *\n * @example\n * ```ts\n * padOctal(0o755) // Returns \"0755\"\n * padOctal(0o644) // Returns \"0644\"\n * ```\n */\nexport function padOctal(mode: number): string {\n  return mode.toString(8).padStart(4, '0')\n}\n\n/**\n * Create a compressed tar stream of files matching a pattern.\n *\n * @param fileName Glob pattern for files to include\n * @param fileContextPath Base directory for resolving file paths\n * @param ignorePatterns Ignore patterns to exclude from the archive\n * @param resolveSymlinks Whether to follow symbolic links\n * @returns A readable stream of the gzipped tar archive\n */\nexport async function tarFileStream(\n  fileName: string,\n  fileContextPath: string,\n  ignorePatterns: string[],\n  resolveSymlinks: boolean\n) {\n  const { create } = await dynamicImport<typeof import('tar')>('tar')\n\n  const allFiles = await getAllFilesInPath(\n    fileName,\n    fileContextPath,\n    ignorePatterns,\n    true\n  )\n\n  const filePaths = allFiles.map((file) => file.relativePosix())\n\n  // gzip.portable ensures deterministic gzip header without affecting file modes\n  return create(\n    {\n      gzip: true,\n      cwd: fileContextPath,\n      follow: resolveSymlinks,\n      noDirRecurse: true,\n    },\n    filePaths\n  )\n}\n\n/**\n * Create a tar stream for upload using chunked transfer encoding.\n *\n * @param fileName Glob pattern for files to include\n * @param fileContextPath Base directory for resolving file paths\n * @param resolveSymlinks Whether to follow symbolic links\n * @returns A readable stream of the gzipped tar archive\n */\nexport async function tarFileStreamUpload(\n  fileName: string,\n  fileContextPath: string,\n  ignorePatterns: string[],\n  resolveSymlinks: boolean\n) {\n  return tarFileStream(\n    fileName,\n    fileContextPath,\n    ignorePatterns,\n    resolveSymlinks\n  )\n}\n\n/**\n * Get the array index for a build step based on its name.\n *\n * Special steps:\n * - BASE_STEP_NAME: Returns 0 (first step)\n * - FINALIZE_STEP_NAME: Returns the last index\n * - Numeric strings: Converted to number\n *\n * @param step Build step name or number as string\n * @param stackTracesLength Total number of stack traces (used for FINALIZE_STEP_NAME)\n * @returns Index for the build step\n */\nexport function getBuildStepIndex(\n  step: string,\n  stackTracesLength: number\n): number {\n  if (step === BASE_STEP_NAME) {\n    return 0\n  }\n\n  if (step === FINALIZE_STEP_NAME) {\n    return stackTracesLength - 1\n  }\n\n  return Number(step)\n}\n\n/**\n * Read GCP service account JSON from a file or object.\n *\n * @param contextPath Base directory for resolving relative file paths\n * @param pathOrContent Either a path to a JSON file or a service account object\n * @returns Service account JSON as a string\n */\nexport function readGCPServiceAccountJSON(\n  contextPath: string,\n  pathOrContent: string | object\n): string {\n  if (typeof pathOrContent === 'string') {\n    return fs.readFileSync(path.join(contextPath, pathOrContent), 'utf-8')\n  }\n  return JSON.stringify(pathOrContent)\n}\n","/**\n * Special step name for the finalization phase of template building.\n * This is the last step that runs after all user-defined instructions.\n * @internal\n */\nexport const FINALIZE_STEP_NAME = 'finalize'\n\n/**\n * Special step name for the base image phase of template building.\n * This is the first step that sets up the base image.\n * @internal\n */\nexport const BASE_STEP_NAME = 'base'\n\n/**\n * Stack trace depth for capturing caller information.\n *\n * Depth levels:\n * 1. Template function\n * 2. TemplateBase class\n * 3. Caller method (e.g., copy(), fromImage(), etc.)\n *\n * This depth is used to determine the original caller's location\n * for stack traces.\n * @internal\n */\nexport const STACK_TRACE_DEPTH = 3\n\n/**\n * Default setting for whether to resolve symbolic links when copying files.\n * When false, symlinks are copied as symlinks rather than following them.\n * @internal\n */\nexport const RESOLVE_SYMLINKS = false\n","import { ApiClient, handleApiError, paths, components } from '../api'\nimport { dynamicImport, stripAnsi } from '../utils'\nimport { BuildError, FileUploadError, TemplateError } from '../errors'\nimport { LogEntry } from './logger'\nimport { getBuildStepIndex, tarFileStreamUpload } from './utils'\nimport {\n  BuildStatusReason,\n  TemplateBuildStatus,\n  TemplateBuildStatusResponse,\n  TemplateTag,\n  TemplateTagInfo,\n} from './types'\n\ntype RequestBuildInput = {\n  name: string\n  tags?: string[]\n  cpuCount: number\n  memoryMB: number\n}\n\ntype GetFileUploadLinkInput = {\n  templateID: string\n  filesHash: string\n}\n\ntype TriggerBuildInput = {\n  templateID: string\n  buildID: string\n  template: TriggerBuildTemplate\n}\n\ntype GetBuildStatusInput = {\n  templateID: string\n  buildID: string\n  logsOffset?: number\n}\n\ntype CheckAliasExistsInput = {\n  alias: string\n}\n\ntype ApiBuildStatusResponse =\n  paths['/templates/{templateID}/builds/{buildID}/status']['get']['responses']['200']['content']['application/json']\n\nexport type TriggerBuildTemplate =\n  paths['/v2/templates/{templateID}/builds/{buildID}']['post']['requestBody']['content']['application/json']\n\nexport async function requestBuild(\n  client: ApiClient,\n  { name, tags, cpuCount, memoryMB }: RequestBuildInput\n) {\n  const requestBuildRes = await client.api.POST('/v3/templates', {\n    body: {\n      name,\n      tags,\n      cpuCount,\n      memoryMB,\n    },\n  })\n\n  const error = handleApiError(requestBuildRes, BuildError)\n  if (error) {\n    throw error\n  }\n\n  if (!requestBuildRes.data) {\n    throw new BuildError('Failed to request build')\n  }\n\n  return requestBuildRes.data\n}\n\nexport async function getFileUploadLink(\n  client: ApiClient,\n  { templateID, filesHash }: GetFileUploadLinkInput,\n  stackTrace?: string\n) {\n  const fileUploadLinkRes = await client.api.GET(\n    '/templates/{templateID}/files/{hash}',\n    {\n      params: {\n        path: {\n          templateID,\n          hash: filesHash,\n        },\n      },\n    }\n  )\n\n  const error = handleApiError(fileUploadLinkRes, FileUploadError, stackTrace)\n  if (error) {\n    throw error\n  }\n\n  if (!fileUploadLinkRes.data) {\n    throw new FileUploadError('Failed to get file upload link', stackTrace)\n  }\n\n  return fileUploadLinkRes.data\n}\n\nexport async function uploadFile(\n  options: {\n    fileName: string\n    fileContextPath: string\n    url: string\n    ignorePatterns: string[]\n    resolveSymlinks: boolean\n  },\n  stackTrace: string | undefined\n) {\n  const { fileName, url, fileContextPath, ignorePatterns, resolveSymlinks } =\n    options\n  try {\n    const uploadStream = await tarFileStreamUpload(\n      fileName,\n      fileContextPath,\n      ignorePatterns,\n      resolveSymlinks\n    )\n\n    // Buffer the archive before uploading so fetch sets Content-Length.\n    // S3 presigned PUT URLs reject Transfer-Encoding: chunked with 501\n    // NotImplemented, which is what Node's fetch falls back to when the\n    // body is a Readable without a known length. See e2b-dev/e2b#1243.\n    // The Python SDK takes the same approach (build_api.py:upload_file).\n    // Dynamically import so the browser bundle doesn't pull in node:stream.\n    // tar's Pack extends Minipass and is iterable as AsyncIterable<Buffer> at\n    // runtime, but the cli's tsconfig (preserveSymlinks) doesn't surface that\n    // through the type chain — cast via unknown.\n    const { buffer } = await dynamicImport<\n      typeof import('node:stream/consumers')\n    >('node:stream/consumers')\n    const uploadBody = await buffer(\n      uploadStream as unknown as AsyncIterable<Buffer>\n    )\n\n    const res = await fetch(url, {\n      method: 'PUT',\n      body: uploadBody,\n    })\n\n    if (!res.ok) {\n      throw new FileUploadError(\n        `Failed to upload file: ${res.statusText}`,\n        stackTrace\n      )\n    }\n  } catch (error) {\n    if (error instanceof FileUploadError) {\n      throw error\n    }\n    throw new FileUploadError(`Failed to upload file: ${error}`, stackTrace)\n  }\n}\n\nexport async function triggerBuild(\n  client: ApiClient,\n  { templateID, buildID, template }: TriggerBuildInput\n) {\n  const triggerBuildRes = await client.api.POST(\n    '/v2/templates/{templateID}/builds/{buildID}',\n    {\n      params: {\n        path: {\n          templateID,\n          buildID,\n        },\n      },\n      body: template,\n    }\n  )\n\n  const error = handleApiError(triggerBuildRes, BuildError)\n  if (error) {\n    throw error\n  }\n}\n\nfunction mapLogEntry(\n  entry: ApiBuildStatusResponse['logEntries'][number]\n): LogEntry {\n  return new LogEntry(new Date(entry.timestamp), entry.level, entry.message)\n}\n\nfunction mapBuildStatusReason(\n  reason: ApiBuildStatusResponse['reason']\n): BuildStatusReason | undefined {\n  if (!reason) {\n    return undefined\n  }\n  return {\n    message: reason.message,\n    step: reason.step,\n    logEntries: (reason.logEntries ?? []).map(mapLogEntry),\n  }\n}\n\nexport async function getBuildStatus(\n  client: ApiClient,\n  { templateID, buildID, logsOffset }: GetBuildStatusInput\n): Promise<TemplateBuildStatusResponse> {\n  const buildStatusRes = await client.api.GET(\n    '/templates/{templateID}/builds/{buildID}/status',\n    {\n      params: {\n        path: {\n          templateID,\n          buildID,\n        },\n        query: {\n          logsOffset,\n        },\n      },\n    }\n  )\n\n  const error = handleApiError(buildStatusRes, BuildError)\n  if (error) {\n    throw error\n  }\n\n  if (!buildStatusRes.data) {\n    throw new BuildError('Failed to get build status')\n  }\n\n  return {\n    buildID: buildStatusRes.data.buildID,\n    templateID: buildStatusRes.data.templateID,\n    status: buildStatusRes.data.status,\n    logEntries: buildStatusRes.data.logEntries.map(mapLogEntry),\n    logs: buildStatusRes.data.logs,\n    reason: mapBuildStatusReason(buildStatusRes.data.reason),\n  }\n}\n\nexport async function checkAliasExists(\n  client: ApiClient,\n  { alias }: CheckAliasExistsInput\n): Promise<boolean> {\n  const aliasRes = await client.api.GET('/templates/aliases/{alias}', {\n    params: {\n      path: {\n        alias,\n      },\n    },\n  })\n\n  // If we get a NotFound, the alias doesn't exist\n  if (aliasRes.response.status === 404) {\n    return false\n  }\n\n  // If we get a Forbidden, alias exists, but you are not owner\n  if (aliasRes.response.status === 403) {\n    return true\n  }\n\n  // Handle other errors\n  const error = handleApiError(aliasRes, TemplateError)\n  if (error) {\n    throw error\n  }\n\n  // If we get Ok with data, you are owner and the alias exists\n  return aliasRes.data !== undefined\n}\n\nexport async function waitForBuildFinish(\n  client: ApiClient,\n  {\n    templateID,\n    buildID,\n    onBuildLogs,\n    logsRefreshFrequency,\n    stackTraces,\n  }: {\n    templateID: string\n    buildID: string\n    onBuildLogs?: (logEntry: LogEntry) => void\n    logsRefreshFrequency: number\n    stackTraces: (string | undefined)[]\n  }\n): Promise<void> {\n  let logsOffset = 0\n  let status: TemplateBuildStatus = 'building'\n\n  while (status === 'building' || status === 'waiting') {\n    const buildStatus = await getBuildStatus(client, {\n      templateID,\n      buildID,\n      logsOffset,\n    })\n\n    logsOffset += buildStatus.logEntries.length\n\n    buildStatus.logEntries.forEach((logEntry) =>\n      onBuildLogs?.(\n        new LogEntry(\n          logEntry.timestamp,\n          logEntry.level,\n          stripAnsi(logEntry.message)\n        )\n      )\n    )\n\n    status = buildStatus.status\n    switch (status) {\n      case 'ready': {\n        return\n      }\n      case 'waiting': {\n        break\n      }\n      case 'error': {\n        let stackError: string | undefined\n        if (buildStatus.reason?.step !== undefined) {\n          const step = getBuildStepIndex(\n            buildStatus.reason.step,\n            stackTraces.length\n          )\n          stackError = stackTraces[step]\n        }\n\n        throw new BuildError(\n          buildStatus?.reason?.message ?? 'Unknown error',\n          stackError\n        )\n      }\n    }\n\n    // Wait for a short period before checking the status again\n    await new Promise((resolve) => setTimeout(resolve, logsRefreshFrequency))\n  }\n\n  throw new BuildError('Unknown build error occurred.')\n}\n\nexport async function assignTags(\n  client: ApiClient,\n  { targetName, tags }: { targetName: string; tags: string[] }\n): Promise<TemplateTagInfo> {\n  const res = await client.api.POST('/templates/tags', {\n    body: { target: targetName, tags },\n  })\n\n  const error = handleApiError(res, TemplateError)\n  if (error) {\n    throw error\n  }\n\n  if (!res.data) {\n    throw new TemplateError('Failed to assign tags')\n  }\n\n  return {\n    buildId: res.data.buildID,\n    tags: res.data.tags,\n  }\n}\n\nexport async function removeTags(\n  client: ApiClient,\n  { name, tags }: { name: string; tags: string[] }\n): Promise<void> {\n  const res = await client.api.DELETE('/templates/tags', {\n    body: { name, tags },\n  })\n\n  const error = handleApiError(res, TemplateError)\n  if (error) {\n    throw error\n  }\n}\n\nexport async function getTemplateTags(\n  client: ApiClient,\n  { templateID }: { templateID: string }\n): Promise<TemplateTag[]> {\n  const res = await client.api.GET('/templates/{templateID}/tags', {\n    params: {\n      path: {\n        templateID,\n      },\n    },\n  })\n\n  const error = handleApiError(res, TemplateError)\n  if (error) {\n    throw error\n  }\n\n  if (!res.data) {\n    throw new TemplateError('Failed to get template tags')\n  }\n\n  return res.data.map((item: components['schemas']['TemplateTag']) => ({\n    tag: item.tag,\n    buildId: item.buildID,\n    createdAt: new Date(item.createdAt),\n  }))\n}\n","import { CopyItem } from './types'\nimport {\n  Argument,\n  DockerfileParser,\n  Instruction as DockerfileInstruction,\n  ModifiableInstruction,\n} from 'dockerfile-ast'\nimport fs from 'node:fs'\nimport { ReadyCmd, waitForTimeout } from './readycmd'\n\nexport interface DockerfileParseResult {\n  baseImage: string\n}\n\ninterface DockerfileFinalParserInterface {}\n\nexport interface DockerfileParserInterface {\n  setWorkdir(workdir: string): DockerfileParserInterface\n  setUser(user: string): DockerfileParserInterface\n  setEnvs(envs: Record<string, string>): DockerfileParserInterface\n  runCmd(\n    commandOrCommands: string | string[],\n    options?: { user?: string }\n  ): DockerfileParserInterface\n  copy(\n    src: string,\n    dest: string,\n    options?: { forceUpload?: true; user?: string; mode?: number }\n  ): DockerfileParserInterface\n  copyItems(\n    items: CopyItem[],\n    options?: { forceUpload?: true; user?: string; mode?: number }\n  ): DockerfileParserInterface\n  setStartCmd(\n    startCommand: string,\n    readyCommand: string | ReadyCmd\n  ): DockerfileFinalParserInterface\n}\n\n/**\n * Parse a Dockerfile and convert it to Template SDK format\n *\n * @param dockerfileContentOrPath Either the Dockerfile content as a string,\n *                                or a path to a Dockerfile file\n * @param templateBuilder Interface providing template builder methods\n * @returns Parsed Dockerfile result with base image and instructions\n */\nexport function parseDockerfile(\n  dockerfileContentOrPath: string,\n  templateBuilder: DockerfileParserInterface\n): DockerfileParseResult {\n  // Check if input is a file path that exists\n  let dockerfileContent: string\n  try {\n    if (\n      fs.existsSync(dockerfileContentOrPath) &&\n      fs.statSync(dockerfileContentOrPath).isFile()\n    ) {\n      // Read the file content\n      dockerfileContent = fs.readFileSync(dockerfileContentOrPath, 'utf-8')\n    } else {\n      // Treat as content directly\n      dockerfileContent = dockerfileContentOrPath\n    }\n  } catch {\n    // If there's any error checking the file, treat as content\n    dockerfileContent = dockerfileContentOrPath\n  }\n\n  const dockerfile = DockerfileParser.parse(dockerfileContent)\n  const instructions = dockerfile.getInstructions()\n\n  // Check for multi-stage builds\n  const fromInstructions = instructions.filter(\n    (instruction) => instruction.getKeyword() === 'FROM'\n  )\n\n  if (fromInstructions.length > 1) {\n    throw new Error('Multi-stage Dockerfiles are not supported')\n  }\n\n  if (fromInstructions.length === 0) {\n    throw new Error('Dockerfile must contain a FROM instruction')\n  }\n\n  // Set the base image from the first FROM instruction\n  const fromInstruction = fromInstructions[0]\n  const argumentsData = fromInstruction.getArguments()\n  let baseImage = 'e2bdev/base' // default fallback\n  let userChanged = false\n  let workdirChanged = false\n  if (argumentsData && argumentsData.length > 0) {\n    baseImage = argumentsData[0].getValue()\n  }\n\n  // Set the user and workdir to the Docker defaults\n  templateBuilder.setUser('root')\n  templateBuilder.setWorkdir('/')\n\n  // Process all other instructions\n  for (const instruction of instructions) {\n    const keyword = instruction.getKeyword()\n\n    switch (keyword) {\n      case 'FROM':\n        // Already handled above\n        break\n\n      case 'RUN':\n        handleRunInstruction(instruction, templateBuilder)\n        break\n\n      case 'COPY':\n      case 'ADD':\n        handleCopyInstruction(\n          instruction as ModifiableInstruction,\n          templateBuilder\n        )\n        break\n\n      case 'WORKDIR':\n        handleWorkdirInstruction(instruction, templateBuilder)\n        workdirChanged = true\n        break\n\n      case 'USER':\n        handleUserInstruction(instruction, templateBuilder)\n        userChanged = true\n        break\n\n      case 'ENV':\n      case 'ARG':\n        handleEnvInstruction(instruction, templateBuilder)\n        break\n\n      case 'EXPOSE':\n        // EXPOSE is not directly supported in our SDK, so we'll skip it\n        break\n\n      case 'VOLUME':\n        // VOLUME is not directly supported in our SDK, so we'll skip it\n        break\n\n      case 'CMD':\n      case 'ENTRYPOINT':\n        handleCmdEntrypointInstruction(instruction, templateBuilder)\n        break\n\n      default:\n        console.warn(`Unsupported instruction: ${keyword}`)\n        break\n    }\n  }\n\n  // Set the user and workdir to the E2B defaults\n  if (!userChanged) {\n    templateBuilder.setUser('user')\n  }\n  if (!workdirChanged) {\n    templateBuilder.setWorkdir('/home/user')\n  }\n\n  return {\n    baseImage,\n  }\n}\n\nfunction handleRunInstruction(\n  instruction: DockerfileInstruction,\n  templateBuilder: DockerfileParserInterface\n): void {\n  const argumentsData = instruction.getArguments()\n  if (argumentsData && argumentsData.length > 0) {\n    const command = argumentsData\n      .map((arg: Argument) => arg.getValue())\n      .join(' ')\n    templateBuilder.runCmd(command)\n  }\n}\n\nfunction handleCopyInstruction(\n  instruction: ModifiableInstruction,\n  templateBuilder: DockerfileParserInterface\n): void {\n  const argumentsData = instruction.getArguments()\n  if (argumentsData && argumentsData.length >= 2) {\n    const src = argumentsData[0].getValue()\n    const dest = argumentsData[argumentsData.length - 1].getValue()\n\n    let user: string | undefined\n    const flags = instruction.getFlags()\n    const chownFlag = flags.find((flag) => flag.getName() === 'chown')\n    if (chownFlag) {\n      user = chownFlag.getValue() ?? undefined\n    }\n\n    templateBuilder.copy(src, dest, { user })\n  }\n}\n\nfunction handleWorkdirInstruction(\n  instruction: DockerfileInstruction,\n  templateBuilder: DockerfileParserInterface\n): void {\n  const argumentsData = instruction.getArguments()\n  if (argumentsData && argumentsData.length > 0) {\n    const workdir = argumentsData[0].getValue()\n    templateBuilder.setWorkdir(workdir)\n  }\n}\n\nfunction handleUserInstruction(\n  instruction: DockerfileInstruction,\n  templateBuilder: DockerfileParserInterface\n): void {\n  const argumentsData = instruction.getArguments()\n  if (argumentsData && argumentsData.length > 0) {\n    const user = argumentsData[0].getValue()\n    templateBuilder.setUser(user)\n  }\n}\n\nfunction handleEnvInstruction(\n  instruction: DockerfileInstruction,\n  templateBuilder: DockerfileParserInterface\n): void {\n  const argumentsData = instruction.getArguments()\n  const keyword = instruction.getKeyword()\n\n  if (argumentsData && argumentsData.length >= 1) {\n    const envVars: Record<string, string> = {}\n\n    if (argumentsData.length === 2) {\n      // ENV key value format OR multiple key=value pairs (from line continuation)\n      const firstArg = argumentsData[0].getValue()\n      const secondArg = argumentsData[1].getValue()\n\n      // Check if both arguments contain '=' (multiple key=value pairs)\n      if (firstArg.includes('=') && secondArg.includes('=')) {\n        // Both are key=value pairs (line continuation)\n        for (const arg of argumentsData) {\n          const envString = arg.getValue()\n          const equalIndex = envString.indexOf('=')\n          if (equalIndex > 0) {\n            const key = envString.substring(0, equalIndex)\n            const value = envString.substring(equalIndex + 1)\n            envVars[key] = value\n          }\n        }\n      } else {\n        // Traditional ENV key value format\n        envVars[firstArg] = secondArg\n      }\n    } else if (argumentsData.length === 1) {\n      // ENV/ARG key=value format (single argument) or ARG key (without default)\n      const envString = argumentsData[0].getValue()\n\n      // Check if it's a simple key=value or just a key (for ARG without default)\n      const equalIndex = envString.indexOf('=')\n      if (equalIndex > 0) {\n        const key = envString.substring(0, equalIndex)\n        const value = envString.substring(equalIndex + 1)\n        envVars[key] = value\n      } else if (keyword === 'ARG' && envString.trim()) {\n        // ARG without default value - set as empty ENV\n        const key = envString.trim()\n        envVars[key] = ''\n      }\n    } else {\n      // Multiple arguments (from line continuation with backslashes)\n      for (const arg of argumentsData) {\n        const envString = arg.getValue()\n        const equalIndex = envString.indexOf('=')\n        if (equalIndex > 0) {\n          const key = envString.substring(0, equalIndex)\n          const value = envString.substring(equalIndex + 1)\n          envVars[key] = value\n        } else if (keyword === 'ARG') {\n          // ARG without default value\n          const key = envString\n          envVars[key] = ''\n        }\n      }\n    }\n\n    // Call setEnvs once with all environment variables from this instruction\n    if (Object.keys(envVars).length > 0) {\n      templateBuilder.setEnvs(envVars)\n    }\n  }\n}\n\nfunction handleCmdEntrypointInstruction(\n  instruction: DockerfileInstruction,\n  templateBuilder: DockerfileParserInterface\n): void {\n  const argumentsData = instruction.getArguments()\n  if (argumentsData && argumentsData.length > 0) {\n    let command = argumentsData.map((arg: Argument) => arg.getValue()).join(' ')\n\n    try {\n      const parsedCommand = JSON.parse(command)\n      if (Array.isArray(parsedCommand)) {\n        command = parsedCommand.join(' ')\n      }\n    } catch {\n      // Do nothing\n    }\n\n    templateBuilder.setStartCmd(command, waitForTimeout(20_000))\n  }\n}\n","/**\n * Class for ready check commands.\n */\nexport class ReadyCmd {\n  private cmd: string\n\n  constructor(cmd: string) {\n    this.cmd = cmd\n  }\n\n  getCmd(): string {\n    return this.cmd\n  }\n}\n\n/**\n * Wait for a port to be listening.\n * Uses `ss` command to check if a port is open and listening.\n *\n * @param port Port number to wait for\n * @returns ReadyCmd that checks for the port\n *\n * @example\n * ```ts\n * import { Template, waitForPort } from 'e2b'\n *\n * const template = Template()\n *   .fromPythonImage()\n *   .setStartCmd('python -m http.server 8000', waitForPort(8000))\n * ```\n */\nexport function waitForPort(port: number): ReadyCmd {\n  const cmd = `ss -tuln | grep :${port}`\n  return new ReadyCmd(cmd)\n}\n\n/**\n * Wait for a URL to return a specific HTTP status code.\n * Uses `curl` to make HTTP requests and check the response status.\n *\n * @param url URL to check (e.g., 'http://localhost:3000/health')\n * @param statusCode Expected HTTP status code (default: 200)\n * @returns ReadyCmd that checks the URL\n *\n * @example\n * ```ts\n * import { Template, waitForURL } from 'e2b'\n *\n * const template = Template()\n *   .fromNodeImage()\n *   .setStartCmd('npm start', waitForURL('http://localhost:3000/health'))\n * ```\n */\nexport function waitForURL(url: string, statusCode: number = 200): ReadyCmd {\n  const cmd = `curl -s -o /dev/null -w \"%{http_code}\" ${url} | grep -q \"${statusCode}\"`\n  return new ReadyCmd(cmd)\n}\n\n/**\n * Wait for a process with a specific name to be running.\n * Uses `pgrep` to check if a process exists.\n *\n * @param processName Name of the process to wait for\n * @returns ReadyCmd that checks for the process\n *\n * @example\n * ```ts\n * import { Template, waitForProcess } from 'e2b'\n *\n * const template = Template()\n *   .fromBaseImage()\n *   .setStartCmd('./my-daemon', waitForProcess('my-daemon'))\n * ```\n */\nexport function waitForProcess(processName: string): ReadyCmd {\n  const cmd = `pgrep ${processName} > /dev/null`\n  return new ReadyCmd(cmd)\n}\n\n/**\n * Wait for a file to exist.\n * Uses shell test command to check file existence.\n *\n * @param filename Path to the file to wait for\n * @returns ReadyCmd that checks for the file\n *\n * @example\n * ```ts\n * import { Template, waitForFile } from 'e2b'\n *\n * const template = Template()\n *   .fromBaseImage()\n *   .setStartCmd('./init.sh', waitForFile('/tmp/ready'))\n * ```\n */\nexport function waitForFile(filename: string): ReadyCmd {\n  const cmd = `[ -f ${filename} ]`\n  return new ReadyCmd(cmd)\n}\n\n/**\n * Wait for a specified timeout before considering the sandbox ready.\n * Uses `sleep` command to wait for a fixed duration.\n *\n * @param timeout Time to wait in milliseconds (minimum: 1000ms / 1 second)\n * @returns ReadyCmd that waits for the specified duration\n *\n * @example\n * ```ts\n * import { Template, waitForTimeout } from 'e2b'\n *\n * const template = Template()\n *   .fromNodeImage()\n *   .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds\n * ```\n */\nexport function waitForTimeout(timeout: number): ReadyCmd {\n  // convert to seconds, but ensure minimum of 1 second\n  const seconds = Math.max(1, Math.floor(timeout / 1000))\n  const cmd = `sleep ${seconds}`\n  return new ReadyCmd(cmd)\n}\n","import type { PathLike } from 'node:fs'\nimport { ApiClient } from '../api'\nimport { ConnectionConfig, ConnectionOpts } from '../connectionConfig'\nimport { BuildError } from '../errors'\nimport { runtime } from '../utils'\nimport {\n  assignTags,\n  checkAliasExists,\n  getTemplateTags,\n  removeTags,\n  getBuildStatus,\n  getFileUploadLink,\n  requestBuild,\n  triggerBuild,\n  TriggerBuildTemplate,\n  uploadFile,\n  waitForBuildFinish,\n} from './buildApi'\nimport { RESOLVE_SYMLINKS, STACK_TRACE_DEPTH } from './consts'\nimport { parseDockerfile } from './dockerfileParser'\nimport { LogEntry, LogEntryEnd, LogEntryStart } from './logger'\nimport { ReadyCmd, waitForFile } from './readycmd'\nimport {\n  BuildInfo,\n  BuildOptions,\n  CopyItem,\n  GetBuildStatusOptions,\n  Instruction,\n  InstructionType,\n  McpServerName,\n  RegistryConfig,\n  TemplateBuilder,\n  TemplateBuildStatusResponse,\n  TemplateClass,\n  TemplateFinal,\n  TemplateFromImage,\n  TemplateOptions,\n  TemplateTag,\n  TemplateTagInfo,\n} from './types'\nimport {\n  calculateFilesHash,\n  getCallerDirectory,\n  getCallerFrame,\n  normalizeBuildArguments,\n  padOctal,\n  readDockerignore,\n  readGCPServiceAccountJSON,\n  validateRelativePath,\n} from './utils'\n\n/**\n * Base class for building E2B sandbox templates.\n */\nexport class TemplateBase\n  implements TemplateFromImage, TemplateBuilder, TemplateFinal\n{\n  private defaultBaseImage: string = 'e2bdev/base'\n  private baseImage: string | undefined = this.defaultBaseImage\n  private baseTemplate: string | undefined = undefined\n  private registryConfig: RegistryConfig | undefined = undefined\n  private startCmd: string | undefined = undefined\n  private readyCmd: string | undefined = undefined\n  // Force the whole template to be rebuilt\n  private force: boolean = false\n  // Force the next layer to be rebuilt\n  private forceNextLayer: boolean = false\n  private instructions: Instruction[] = []\n  private fileContextPath: PathLike =\n    runtime === 'browser' ? '.' : (getCallerDirectory(STACK_TRACE_DEPTH) ?? '.')\n  private fileIgnorePatterns: string[] = []\n  private logsRefreshFrequency: number = 200\n  private stackTraces: (string | undefined)[] = []\n  private stackTracesEnabled: boolean = true\n  private stackTracesOverride: string | undefined = undefined\n\n  constructor(options?: TemplateOptions) {\n    this.fileContextPath = options?.fileContextPath ?? this.fileContextPath\n    this.fileIgnorePatterns =\n      options?.fileIgnorePatterns ?? this.fileIgnorePatterns\n  }\n\n  /**\n   * Convert a template to JSON representation.\n   *\n   * @param template The template to convert\n   * @param computeHashes Whether to compute file hashes for cache invalidation\n   * @returns JSON string representation of the template\n   */\n  static toJSON(\n    template: TemplateClass,\n    computeHashes: boolean = true\n  ): Promise<string> {\n    return (template as TemplateBase).toJSON(computeHashes)\n  }\n\n  /**\n   * Convert a template to Dockerfile format.\n   * Note: Templates based on other E2B templates cannot be converted to Dockerfile.\n   *\n   * @param template The template to convert\n   * @returns Dockerfile string representation\n   * @throws Error if the template is based on another E2B template\n   */\n  static toDockerfile(template: TemplateClass): string {\n    return (template as TemplateBase).toDockerfile()\n  }\n\n  /**\n   * Build and deploy a template to E2B infrastructure.\n   *\n   * @param template The template to build\n   * @param name Template name in 'name' or 'name:tag' format\n   * @param options Optional build configuration options\n   *\n   * @example\n   * ```ts\n   * const template = Template().fromPythonImage('3')\n   *\n   * // Build with single tag in name\n   * await Template.build(template, 'my-python-env:v1.0')\n   *\n   * // Build with multiple tags\n   * await Template.build(template, 'my-python-env', { tags: ['v1.0', 'stable'] })\n   * ```\n   */\n  static async build(\n    template: TemplateClass,\n    name: string,\n    options?: Omit<BuildOptions, 'alias'>\n  ): Promise<BuildInfo>\n  /**\n   * Build and deploy a template to E2B infrastructure.\n   *\n   * @param template The template to build\n   * @param options Build configuration options with alias (deprecated)\n   *\n   * @deprecated Use the overload with `name` parameter instead.\n   * @example\n   * ```ts\n   * // Deprecated:\n   * await Template.build(template, { alias: 'my-python-env' })\n   *\n   * // Use instead:\n   * await Template.build(template, 'my-python-env:v1.0')\n   * ```\n   */\n  static async build(\n    template: TemplateClass,\n    options: BuildOptions\n  ): Promise<BuildInfo>\n  static async build(\n    template: TemplateClass,\n    nameOrOptions: string | BuildOptions,\n    options?: Omit<BuildOptions, 'alias'>\n  ): Promise<BuildInfo> {\n    const { name, buildOptions } = normalizeBuildArguments(\n      nameOrOptions,\n      options\n    )\n\n    try {\n      buildOptions.onBuildLogs?.(new LogEntryStart(new Date(), 'Build started'))\n      const baseTemplate = template as TemplateBase\n\n      const config = new ConnectionConfig(buildOptions)\n      const client = new ApiClient(config)\n\n      const data = await baseTemplate.build(client, name, buildOptions)\n\n      buildOptions.onBuildLogs?.(\n        new LogEntry(new Date(), 'info', 'Waiting for logs...')\n      )\n\n      await waitForBuildFinish(client, {\n        templateID: data.templateId,\n        buildID: data.buildId,\n        onBuildLogs: buildOptions.onBuildLogs,\n        logsRefreshFrequency: baseTemplate.logsRefreshFrequency,\n        stackTraces: baseTemplate.stackTraces,\n      })\n\n      return data\n    } finally {\n      buildOptions.onBuildLogs?.(new LogEntryEnd(new Date(), 'Build finished'))\n    }\n  }\n\n  /**\n   * Build and deploy a template to E2B infrastructure without waiting for completion.\n   *\n   * @param template The template to build\n   * @param name Template name in 'name' or 'name:tag' format\n   * @param options Optional build configuration options\n   *\n   * @example\n   * ```ts\n   * const template = Template().fromPythonImage('3')\n   *\n   * // Build with single tag in name\n   * const data = await Template.buildInBackground(template, 'my-python-env:v1.0')\n   *\n   * // Build with multiple tags\n   * const data = await Template.buildInBackground(template, 'my-python-env', { tags: ['v1.0', 'stable'] })\n   * ```\n   */\n  static async buildInBackground(\n    template: TemplateClass,\n    name: string,\n    options?: Omit<BuildOptions, 'alias'>\n  ): Promise<BuildInfo>\n  /**\n   * Build and deploy a template to E2B infrastructure without waiting for completion.\n   *\n   * @param template The template to build\n   * @param options Build configuration options with alias (deprecated)\n   *\n   * @deprecated Use the overload with `name` parameter instead.\n   * @example\n   * ```ts\n   * // Deprecated:\n   * await Template.buildInBackground(template, { alias: 'my-python-env' })\n   *\n   * // Use instead:\n   * await Template.buildInBackground(template, 'my-python-env:v1.0')\n   * ```\n   */\n  static async buildInBackground(\n    template: TemplateClass,\n    options: BuildOptions\n  ): Promise<BuildInfo>\n  static async buildInBackground(\n    template: TemplateClass,\n    nameOrOptions: string | BuildOptions,\n    options?: Omit<BuildOptions, 'alias'>\n  ): Promise<BuildInfo> {\n    const { name, buildOptions } = normalizeBuildArguments(\n      nameOrOptions,\n      options\n    )\n\n    const config = new ConnectionConfig(buildOptions)\n    const client = new ApiClient(config)\n\n    return (template as TemplateBase).build(client, name, buildOptions)\n  }\n\n  /**\n   * Get the status of a build.\n   *\n   * @param data Build identifiers\n   * @param options Authentication options\n   *\n   * @example\n   * ```ts\n   * const status = await Template.getBuildStatus(data, { logsOffset: 0 })\n   * ```\n   */\n  static async getBuildStatus(\n    data: Pick<BuildInfo, 'templateId' | 'buildId'>,\n    options?: GetBuildStatusOptions\n  ): Promise<TemplateBuildStatusResponse> {\n    const config = new ConnectionConfig(options)\n    const client = new ApiClient(config)\n\n    return await getBuildStatus(client, {\n      templateID: data.templateId,\n      buildID: data.buildId,\n      logsOffset: options?.logsOffset,\n    })\n  }\n\n  /**\n   * Check if a template with the given name exists.\n   *\n   * @param name Template name to check\n   * @param options Authentication options\n   * @returns True if the name exists, false otherwise\n   *\n   * @example\n   * ```ts\n   * const exists = await Template.exists('my-python-env')\n   * if (exists) {\n   *   console.log('Template exists!')\n   * }\n   * ```\n   */\n  static async exists(\n    name: string,\n    options?: ConnectionOpts\n  ): Promise<boolean> {\n    return TemplateBase.aliasExists(name, options)\n  }\n\n  /**\n   * Check if a template with the given alias exists.\n   *\n   * @param alias Template alias to check\n   * @param options Authentication options\n   * @returns True if the alias exists, false otherwise\n   *\n   * @deprecated Use `exists` instead.\n   * @example\n   * ```ts\n   * const exists = await Template.aliasExists('my-python-env')\n   * if (exists) {\n   *   console.log('Template exists!')\n   * }\n   * ```\n   */\n  static async aliasExists(\n    alias: string,\n    options?: ConnectionOpts\n  ): Promise<boolean> {\n    const config = new ConnectionConfig(options)\n    const client = new ApiClient(config)\n\n    return checkAliasExists(client, { alias })\n  }\n\n  /**\n   * Assign tag(s) to an existing template build.\n   *\n   * @param targetName Template name in 'name:tag' format (the source build to tag from)\n   * @param tags Tag or tags to assign\n   * @param options Authentication options\n   * @returns Tag info with buildId and assigned tags\n   *\n   * @example\n   * ```ts\n   * // Assign a single tag\n   * await Template.assignTags('my-template:v1.0', 'production')\n   *\n   * // Assign multiple tags\n   * await Template.assignTags('my-template:v1.0', ['production', 'stable'])\n   * ```\n   */\n  static async assignTags(\n    targetName: string,\n    tags: string | string[],\n    options?: ConnectionOpts\n  ): Promise<TemplateTagInfo> {\n    const config = new ConnectionConfig(options)\n    const client = new ApiClient(config)\n    const normalizedTags = Array.isArray(tags) ? tags : [tags]\n    return assignTags(client, { targetName, tags: normalizedTags })\n  }\n\n  /**\n   * Remove tag(s) from a template.\n   *\n   * @param name Template name\n   * @param tags Tag or tags to remove\n   * @param options Authentication options\n   *\n   * @example\n   * ```ts\n   * // Remove a single tag\n   * await Template.removeTags('my-template', 'production')\n   *\n   * // Remove multiple tags from a template\n   * await Template.removeTags('my-template', ['production', 'staging'])\n   * ```\n   */\n  static async removeTags(\n    name: string,\n    tags: string | string[],\n    options?: ConnectionOpts\n  ): Promise<void> {\n    const config = new ConnectionConfig(options)\n    const client = new ApiClient(config)\n    const normalizedTags = Array.isArray(tags) ? tags : [tags]\n    return removeTags(client, { name, tags: normalizedTags })\n  }\n\n  /**\n   * Get all tags for a template.\n   *\n   * @param templateId Template ID or name\n   * @param options Authentication options\n   * @returns Array of tag details including tag name, buildId, and creation date\n   *\n   * @example\n   * ```ts\n   * const tags = await Template.getTags('my-template')\n   * for (const tag of tags) {\n   *   console.log(`Tag: ${tag.tag}, Build: ${tag.buildId}, Created: ${tag.createdAt}`)\n   * }\n   * ```\n   */\n  static async getTags(\n    templateId: string,\n    options?: ConnectionOpts\n  ): Promise<TemplateTag[]> {\n    const config = new ConnectionConfig(options)\n    const client = new ApiClient(config)\n    return getTemplateTags(client, { templateID: templateId })\n  }\n\n  fromDebianImage(variant: string = 'stable'): TemplateBuilder {\n    return this.fromImage(`debian:${variant}`)\n  }\n\n  fromUbuntuImage(variant: string = 'latest'): TemplateBuilder {\n    return this.fromImage(`ubuntu:${variant}`)\n  }\n\n  fromPythonImage(version: string = '3'): TemplateBuilder {\n    return this.fromImage(`python:${version}`)\n  }\n\n  fromNodeImage(variant: string = 'lts'): TemplateBuilder {\n    return this.fromImage(`node:${variant}`)\n  }\n\n  fromBunImage(variant: string = 'latest'): TemplateBuilder {\n    return this.fromImage(`oven/bun:${variant}`)\n  }\n\n  fromBaseImage(): TemplateBuilder {\n    return this.fromImage(this.defaultBaseImage)\n  }\n\n  fromImage(\n    baseImage: string,\n    credentials?: { username: string; password: string }\n  ): TemplateBuilder {\n    this.baseImage = baseImage\n    this.baseTemplate = undefined\n\n    // Set the registry config if provided\n    if (credentials) {\n      this.registryConfig = {\n        type: 'registry',\n        username: credentials.username,\n        password: credentials.password,\n      }\n    }\n\n    // If we should force the next layer and it's a FROM command, invalidate whole template\n    if (this.forceNextLayer) {\n      this.force = true\n    }\n\n    this.collectStackTrace()\n    return this\n  }\n\n  fromTemplate(template: string): TemplateBuilder {\n    this.baseTemplate = template\n    this.baseImage = undefined\n\n    // If we should force the next layer and it's a FROM command, invalidate whole template\n    if (this.forceNextLayer) {\n      this.force = true\n    }\n\n    this.collectStackTrace()\n    return this\n  }\n\n  fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder {\n    const { baseImage } = this.runInStackTraceOverrideContext(\n      () => parseDockerfile(dockerfileContentOrPath, this),\n      // -1 as we're going up the call stack from the parseDockerfile function\n      getCallerFrame(STACK_TRACE_DEPTH - 1)\n    )\n    this.baseImage = baseImage\n    this.baseTemplate = undefined\n\n    // If we should force the next layer and it's a FROM command, invalidate whole template\n    if (this.forceNextLayer) {\n      this.force = true\n    }\n\n    this.collectStackTrace()\n    return this\n  }\n\n  fromAWSRegistry(\n    image: string,\n    credentials: {\n      accessKeyId: string\n      secretAccessKey: string\n      region: string\n    }\n  ): TemplateBuilder {\n    this.baseImage = image\n    this.baseTemplate = undefined\n\n    // Set the registry config if provided\n    this.registryConfig = {\n      type: 'aws',\n      awsAccessKeyId: credentials.accessKeyId,\n      awsSecretAccessKey: credentials.secretAccessKey,\n      awsRegion: credentials.region,\n    }\n\n    // If we should force the next layer and it's a FROM command, invalidate whole template\n    if (this.forceNextLayer) {\n      this.force = true\n    }\n\n    this.collectStackTrace()\n    return this\n  }\n\n  fromGCPRegistry(\n    image: string,\n    credentials: {\n      serviceAccountJSON: string | object\n    }\n  ): TemplateBuilder {\n    this.baseImage = image\n    this.baseTemplate = undefined\n\n    // Set the registry config if provided\n    this.registryConfig = {\n      type: 'gcp',\n      serviceAccountJson: readGCPServiceAccountJSON(\n        this.fileContextPath.toString(),\n        credentials.serviceAccountJSON\n      ),\n    }\n\n    // If we should force the next layer and it's a FROM command, invalidate whole template\n    if (this.forceNextLayer) {\n      this.force = true\n    }\n\n    this.collectStackTrace()\n    return this\n  }\n\n  copy(\n    src: PathLike | PathLike[],\n    dest: PathLike,\n    options?: {\n      forceUpload?: true\n      user?: string\n      mode?: number\n      resolveSymlinks?: boolean\n    }\n  ): TemplateBuilder {\n    if (runtime === 'browser') {\n      throw new Error('Browser runtime is not supported for copy')\n    }\n\n    const srcs = Array.isArray(src) ? src : [src]\n    const stackTrace = getCallerFrame(STACK_TRACE_DEPTH - 1)\n\n    for (const src of srcs) {\n      const srcString = src.toString()\n\n      // Validate that the source path is a relative path within the context directory\n      validateRelativePath(srcString, stackTrace)\n\n      const args = [\n        srcString,\n        dest.toString(),\n        options?.user ?? '',\n        options?.mode ? padOctal(options.mode) : '',\n      ]\n\n      this.instructions.push({\n        type: InstructionType.COPY,\n        args,\n        force: options?.forceUpload || this.forceNextLayer,\n        forceUpload: options?.forceUpload,\n        resolveSymlinks: options?.resolveSymlinks,\n      })\n    }\n\n    this.collectStackTrace()\n    return this\n  }\n\n  copyItems(items: CopyItem[]): TemplateBuilder {\n    if (runtime === 'browser') {\n      throw new Error('Browser runtime is not supported for copyItems')\n    }\n\n    // Stack trace that will be used to re-throw the error with\n    const stackTrace = getCallerFrame(STACK_TRACE_DEPTH - 1)\n\n    this.runInNewStackTraceContext(() => {\n      for (const item of items) {\n        try {\n          this.copy(item.src, item.dest, {\n            forceUpload: item.forceUpload,\n            user: item.user,\n            mode: item.mode,\n            resolveSymlinks: item.resolveSymlinks,\n          })\n        } catch (error) {\n          const copyError = error as Error\n          copyError.stack = stackTrace\n          throw copyError\n        }\n      }\n    })\n\n    return this\n  }\n\n  remove(\n    path: PathLike | PathLike[],\n    options?: { force?: boolean; recursive?: boolean; user?: string }\n  ): TemplateBuilder {\n    const paths = Array.isArray(path) ? path : [path]\n    const args = ['rm']\n    if (options?.recursive) {\n      args.push('-r')\n    }\n    if (options?.force) {\n      args.push('-f')\n    }\n    args.push(...paths.map((p) => p.toString()))\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(args.join(' '), { user: options?.user })\n    )\n  }\n\n  rename(\n    src: PathLike,\n    dest: PathLike,\n    options?: { force?: boolean; user?: string }\n  ): TemplateBuilder {\n    const args = ['mv', src.toString(), dest.toString()]\n    if (options?.force) {\n      args.push('-f')\n    }\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(args.join(' '), { user: options?.user })\n    )\n  }\n\n  makeDir(\n    path: PathLike | PathLike[],\n    options?: { mode?: number; user?: string }\n  ): TemplateBuilder {\n    const paths = Array.isArray(path) ? path : [path]\n    const args = ['mkdir', '-p']\n    if (options?.mode) {\n      args.push(`-m ${padOctal(options.mode)}`)\n    }\n    args.push(...paths.map((p) => p.toString()))\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(args.join(' '), { user: options?.user })\n    )\n  }\n\n  makeSymlink(\n    src: PathLike,\n    dest: PathLike,\n    options?: { user?: string; force?: boolean }\n  ): TemplateBuilder {\n    const args = ['ln', '-s']\n    if (options?.force) {\n      args.push('-f')\n    }\n    args.push(src.toString(), dest.toString())\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(args.join(' '), { user: options?.user })\n    )\n  }\n\n  runCmd(command: string, options?: { user?: string }): TemplateBuilder\n  runCmd(commands: string[], options?: { user?: string }): TemplateBuilder\n  runCmd(\n    commandOrCommands: string | string[],\n    options?: { user?: string }\n  ): TemplateBuilder {\n    const cmds = Array.isArray(commandOrCommands)\n      ? commandOrCommands\n      : [commandOrCommands]\n\n    const args = [cmds.join(' && ')]\n    if (options?.user) {\n      args.push(options.user)\n    }\n\n    this.instructions.push({\n      type: InstructionType.RUN,\n      args,\n      force: this.forceNextLayer,\n    })\n\n    this.collectStackTrace()\n    return this\n  }\n\n  setWorkdir(workdir: PathLike): TemplateBuilder {\n    this.instructions.push({\n      type: InstructionType.WORKDIR,\n      args: [workdir.toString()],\n      force: this.forceNextLayer,\n    })\n\n    this.collectStackTrace()\n    return this\n  }\n\n  setUser(user: string): TemplateBuilder {\n    this.instructions.push({\n      type: InstructionType.USER,\n      args: [user],\n      force: this.forceNextLayer,\n    })\n\n    this.collectStackTrace()\n    return this\n  }\n\n  pipInstall(\n    packages?: string | string[],\n    options?: { g?: boolean }\n  ): TemplateBuilder {\n    const g = options?.g ?? true\n\n    const args = ['pip', 'install']\n    const packageList = packages\n      ? Array.isArray(packages)\n        ? packages\n        : [packages]\n      : undefined\n    if (g === false) {\n      args.push('--user')\n    }\n    if (packageList) {\n      args.push(...packageList)\n    } else {\n      args.push('.')\n    }\n\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(args.join(' '), {\n        user: g ? 'root' : undefined,\n      })\n    )\n  }\n\n  npmInstall(\n    packages?: string | string[],\n    options?: { g?: boolean; dev?: boolean }\n  ): TemplateBuilder {\n    const args = ['npm', 'install']\n    const packageList = packages\n      ? Array.isArray(packages)\n        ? packages\n        : [packages]\n      : undefined\n    if (options?.g) {\n      args.push('-g')\n    }\n    if (options?.dev) {\n      args.push('--save-dev')\n    }\n    if (packageList) {\n      args.push(...packageList)\n    }\n\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(args.join(' '), {\n        user: options?.g ? 'root' : undefined,\n      })\n    )\n  }\n\n  bunInstall(\n    packages?: string | string[],\n    options?: { g?: boolean; dev?: boolean }\n  ): TemplateBuilder {\n    const args = ['bun', 'install']\n    const packageList = packages\n      ? Array.isArray(packages)\n        ? packages\n        : [packages]\n      : undefined\n    if (options?.g) {\n      args.push('-g')\n    }\n    if (options?.dev) {\n      args.push('--dev')\n    }\n    if (packageList) {\n      args.push(...packageList)\n    }\n\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(args.join(' '), {\n        user: options?.g ? 'root' : undefined,\n      })\n    )\n  }\n\n  aptInstall(\n    packages: string | string[],\n    options?: { noInstallRecommends?: boolean; fixMissing?: boolean }\n  ): TemplateBuilder {\n    const packageList = Array.isArray(packages) ? packages : [packages]\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(\n        [\n          'apt-get update',\n          `DEBIAN_FRONTEND=noninteractive DEBCONF_NOWARNINGS=yes apt-get install -y ${options?.noInstallRecommends ? '--no-install-recommends ' : ''}${options?.fixMissing ? '--fix-missing ' : ''}${packageList.join(\n            ' '\n          )}`,\n        ],\n        { user: 'root' }\n      )\n    )\n  }\n\n  addMcpServer(servers: McpServerName | McpServerName[]): TemplateBuilder {\n    if (this.baseTemplate !== 'mcp-gateway') {\n      throw new BuildError(\n        'MCP servers can only be added to mcp-gateway template',\n        getCallerFrame(STACK_TRACE_DEPTH - 1)\n      )\n    }\n\n    const serverList = Array.isArray(servers) ? servers : [servers]\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(`mcp-gateway pull ${serverList.join(' ')}`, {\n        user: 'root',\n      })\n    )\n  }\n\n  gitClone(\n    url: string,\n    path?: PathLike,\n    options?: { branch?: string; depth?: number; user?: string }\n  ): TemplateBuilder {\n    const args = ['git', 'clone', url]\n    if (options?.branch) {\n      args.push(`--branch ${options.branch}`)\n      args.push('--single-branch')\n    }\n    if (options?.depth) {\n      args.push(`--depth ${options.depth}`)\n    }\n    if (path) {\n      args.push(path.toString())\n    }\n\n    return this.runInNewStackTraceContext(() =>\n      this.runCmd(args.join(' '), { user: options?.user })\n    )\n  }\n\n  setStartCmd(\n    startCommand: string,\n    readyCommand: string | ReadyCmd\n  ): TemplateFinal {\n    this.startCmd = startCommand\n\n    if (readyCommand instanceof ReadyCmd) {\n      this.readyCmd = readyCommand.getCmd()\n    } else {\n      this.readyCmd = readyCommand\n    }\n\n    this.collectStackTrace()\n    return this\n  }\n\n  setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal {\n    if (readyCommand instanceof ReadyCmd) {\n      this.readyCmd = readyCommand.getCmd()\n    } else {\n      this.readyCmd = readyCommand\n    }\n\n    this.collectStackTrace()\n    return this\n  }\n\n  setEnvs(envs: Record<string, string>): TemplateBuilder {\n    if (Object.keys(envs).length === 0) {\n      return this\n    }\n\n    this.instructions.push({\n      type: InstructionType.ENV,\n      args: Object.entries(envs).flatMap(([key, value]) => [key, value]),\n      force: this.forceNextLayer,\n    })\n    this.collectStackTrace()\n    return this\n  }\n\n  skipCache(): this {\n    this.forceNextLayer = true\n    return this\n  }\n\n  betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder {\n    if (this.baseTemplate !== 'devcontainer') {\n      throw new BuildError(\n        'Devcontainers can only used in the devcontainer template',\n        getCallerFrame(STACK_TRACE_DEPTH - 1)\n      )\n    }\n\n    return this.runInNewStackTraceContext(() => {\n      return this.runCmd(\n        `devcontainer build --workspace-folder ${devcontainerDirectory}`,\n        { user: 'root' }\n      )\n    })\n  }\n\n  betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal {\n    if (this.baseTemplate !== 'devcontainer') {\n      throw new BuildError(\n        'Devcontainers can only used in the devcontainer template',\n        getCallerFrame(STACK_TRACE_DEPTH - 1)\n      )\n    }\n\n    return this.runInNewStackTraceContext(() => {\n      return this.setStartCmd(\n        `sudo devcontainer up --workspace-folder ${devcontainerDirectory} && sudo /prepare-exec.sh ${devcontainerDirectory} | sudo tee /devcontainer.sh > /dev/null && sudo chmod +x /devcontainer.sh && sudo touch /devcontainer.up`,\n        waitForFile('/devcontainer.up')\n      )\n    })\n  }\n\n  /**\n   * Collect the current stack trace for debugging purposes.\n   *\n   * @param stackTracesDepth Depth to traverse in the call stack\n   * @returns this for method chaining\n   */\n  private collectStackTrace(stackTracesDepth: number = STACK_TRACE_DEPTH) {\n    if (!this.stackTracesEnabled) {\n      return this\n    }\n\n    if (this.stackTracesOverride) {\n      this.stackTraces.push(this.stackTracesOverride)\n      return this\n    }\n\n    this.stackTraces.push(getCallerFrame(stackTracesDepth))\n    return this\n  }\n\n  /**\n   * Temporarily disable stack trace collection.\n   *\n   * @returns this for method chaining\n   */\n  private disableStackTrace() {\n    this.stackTracesEnabled = false\n    return this\n  }\n\n  /**\n   * Re-enable stack trace collection.\n   *\n   * @returns this for method chaining\n   */\n  private enableStackTrace() {\n    this.stackTracesEnabled = true\n    return this\n  }\n\n  /**\n   * Execute a function in a clean stack trace context.\n   *\n   * @param fn Function to execute\n   * @returns The result of the function\n   */\n  private runInNewStackTraceContext<T>(fn: () => T): T {\n    this.disableStackTrace()\n    const result = fn()\n    this.enableStackTrace()\n    this.collectStackTrace(STACK_TRACE_DEPTH + 1)\n    return result\n  }\n\n  private runInStackTraceOverrideContext<T>(\n    fn: () => T,\n    stackTraceOverride: string | undefined\n  ): T {\n    this.stackTracesOverride = stackTraceOverride\n    const result = fn()\n    this.stackTracesOverride = undefined\n    return result\n  }\n\n  /**\n   * Convert the template to JSON representation.\n   *\n   * @param computeHashes Whether to compute file hashes for COPY instructions\n   * @returns JSON string representation of the template\n   */\n  private async toJSON(computeHashes: boolean): Promise<string> {\n    let instructions = this.instructions\n    if (computeHashes) {\n      instructions = await this.instructionsWithHashes()\n    }\n\n    return JSON.stringify(this.serialize(instructions), undefined, 2)\n  }\n\n  /**\n   * Convert the template to Dockerfile format.\n   *\n   * Note: Only templates based on Docker images can be converted to Dockerfile.\n   * Templates based on other E2B templates cannot be converted because they\n   * may use features not available in standard Dockerfiles.\n   *\n   * @returns Dockerfile string representation\n   * @throws Error if template is based on another E2B template or has no base image\n   */\n  private toDockerfile(): string {\n    if (this.baseTemplate !== undefined) {\n      throw new Error(\n        'Cannot convert template built from another template to Dockerfile. ' +\n          'Templates based on other templates can only be built using the E2B API.'\n      )\n    }\n\n    if (this.baseImage === undefined) {\n      throw new Error('No base image specified for template')\n    }\n\n    let dockerfile = `FROM ${this.baseImage}\\n`\n    for (const instruction of this.instructions) {\n      if (instruction.type === InstructionType.RUN) {\n        dockerfile += `RUN ${instruction.args[0]}\\n`\n        continue\n      }\n      if (instruction.type === InstructionType.COPY) {\n        dockerfile += `COPY ${instruction.args[0]} ${instruction.args[1]}\\n`\n        continue\n      }\n      if (instruction.type === InstructionType.ENV) {\n        const values: string[] = []\n        for (let i = 0; i < instruction.args.length; i += 2) {\n          values.push(`${instruction.args[i]}=${instruction.args[i + 1]}`)\n        }\n        dockerfile += `ENV ${values.join(' ')}\\n`\n        continue\n      }\n      dockerfile += `${instruction.type} ${instruction.args.join(' ')}\\n`\n    }\n    if (this.startCmd) {\n      dockerfile += `ENTRYPOINT ${this.startCmd}\\n`\n    }\n    return dockerfile\n  }\n\n  /**\n   * Internal implementation of the template build process.\n   *\n   * @param client API client for communicating with E2B backend\n   * @param name Template name in 'name' or 'name:tag' format\n   * @param tags Additional tags to assign to the build\n   * @param options Build configuration options\n   * @throws BuildError if the build fails\n   */\n  private async build(\n    client: ApiClient,\n    name: string,\n    options: Omit<BuildOptions, 'alias'>\n  ): Promise<BuildInfo> {\n    if (options.skipCache) {\n      this.force = true\n    }\n\n    // Create template\n    options.onBuildLogs?.(\n      new LogEntry(\n        new Date(),\n        'info',\n        `Requesting build for template: ${name}${options.tags && options.tags.length > 0 ? ` with tags ${options.tags.join(', ')}` : ''}`\n      )\n    )\n\n    const {\n      templateID,\n      buildID,\n      tags: responseTags,\n    } = await requestBuild(client, {\n      name,\n      tags: options.tags,\n      cpuCount: options.cpuCount ?? 2,\n      memoryMB: options.memoryMB ?? 1024,\n    })\n\n    options.onBuildLogs?.(\n      new LogEntry(\n        new Date(),\n        'info',\n        `Template created with ID: ${templateID}, Build ID: ${buildID}`\n      )\n    )\n\n    const instructionsWithHashes = await this.instructionsWithHashes()\n\n    // Upload files in parallel\n    const uploadPromises = instructionsWithHashes.map(\n      async (instruction, index) => {\n        if (instruction.type !== InstructionType.COPY) {\n          return\n        }\n\n        const src = instruction.args.length > 0 ? instruction.args[0] : null\n        const filesHash = instruction.filesHash ?? null\n        if (src === null || filesHash === null) {\n          throw new Error('Source path and files hash are required')\n        }\n\n        const forceUpload = instruction.forceUpload\n        let stackTrace = undefined\n        if (index + 1 >= 0 && index + 1 < this.stackTraces.length) {\n          stackTrace = this.stackTraces[index + 1]\n        }\n\n        const { present, url } = await getFileUploadLink(\n          client,\n          {\n            templateID,\n            filesHash,\n          },\n          stackTrace\n        )\n\n        if (\n          (forceUpload && url != null) ||\n          (present === false && url != null)\n        ) {\n          await uploadFile(\n            {\n              fileName: src,\n              fileContextPath: this.fileContextPath.toString(),\n              url,\n              ignorePatterns: [\n                ...this.fileIgnorePatterns,\n                ...readDockerignore(this.fileContextPath.toString()),\n              ],\n              resolveSymlinks: instruction.resolveSymlinks ?? RESOLVE_SYMLINKS,\n            },\n            stackTrace\n          )\n          options.onBuildLogs?.(\n            new LogEntry(new Date(), 'info', `Uploaded '${src}'`)\n          )\n        } else {\n          options.onBuildLogs?.(\n            new LogEntry(\n              new Date(),\n              'info',\n              `Skipping upload of '${src}', already cached`\n            )\n          )\n        }\n      }\n    )\n\n    await Promise.all(uploadPromises)\n\n    options.onBuildLogs?.(\n      new LogEntry(new Date(), 'info', 'All file uploads completed')\n    )\n\n    // Start build\n    options.onBuildLogs?.(\n      new LogEntry(new Date(), 'info', 'Starting building...')\n    )\n\n    await triggerBuild(client, {\n      templateID,\n      buildID,\n      template: this.serialize(instructionsWithHashes),\n    })\n\n    return {\n      alias: name,\n      name: name,\n      tags: responseTags,\n      templateId: templateID,\n      buildId: buildID,\n    }\n  }\n\n  /**\n   * Add file hashes to COPY instructions for cache invalidation.\n   *\n   * @returns Copy of instructions array with filesHash added to COPY instructions\n   */\n  private async instructionsWithHashes(): Promise<Instruction[]> {\n    return Promise.all(\n      this.instructions.map(async (instruction, index) => {\n        if (instruction.type !== InstructionType.COPY) {\n          return instruction\n        }\n\n        const src = instruction.args.length > 0 ? instruction.args[0] : null\n        const dest = instruction.args.length > 1 ? instruction.args[1] : null\n        if (src === null || dest === null) {\n          throw new Error('Source path and destination path are required')\n        }\n\n        let stackTrace = undefined\n        if (index + 1 >= 0 && index + 1 < this.stackTraces.length) {\n          stackTrace = this.stackTraces[index + 1]\n        }\n\n        return {\n          ...instruction,\n          filesHash: await calculateFilesHash(\n            src,\n            dest,\n            this.fileContextPath.toString(),\n            [\n              ...this.fileIgnorePatterns,\n              ...(runtime === 'browser'\n                ? []\n                : readDockerignore(this.fileContextPath.toString())),\n            ],\n            instruction.resolveSymlinks ?? RESOLVE_SYMLINKS,\n            stackTrace\n          ),\n        }\n      })\n    )\n  }\n\n  /**\n   * Serialize the template to the API request format.\n   *\n   * @param steps Array of build instructions with file hashes\n   * @returns Template data formatted for the API\n   */\n  private serialize(steps: Instruction[]): TriggerBuildTemplate {\n    const templateData: TriggerBuildTemplate = {\n      startCmd: this.startCmd,\n      readyCmd: this.readyCmd,\n      steps,\n      force: this.force,\n    }\n\n    if (this.baseImage !== undefined) {\n      templateData.fromImage = this.baseImage\n    }\n\n    if (this.baseTemplate !== undefined) {\n      templateData.fromTemplate = this.baseTemplate\n    }\n\n    if (this.registryConfig !== undefined) {\n      templateData.fromImageRegistry = this.registryConfig\n    }\n\n    return templateData\n  }\n}\n\n/**\n * Create a new E2B template builder instance.\n *\n * @param options Optional configuration for the template builder\n * @returns A new template builder instance\n *\n * @example\n * ```ts\n * import { Template } from 'e2b'\n *\n * const template = Template()\n *   .fromPythonImage('3')\n *   .copy('requirements.txt', '/app/')\n *   .pipInstall()\n *\n * await Template.build(template, 'my-python-app:v1.0')\n * ```\n */\nexport function Template(options?: TemplateOptions): TemplateFromImage {\n  return new TemplateBase(options)\n}\n\nTemplate.build = TemplateBase.build\nTemplate.buildInBackground = TemplateBase.buildInBackground\nTemplate.getBuildStatus = TemplateBase.getBuildStatus\nTemplate.exists = TemplateBase.exists\nTemplate.aliasExists = TemplateBase.aliasExists\nTemplate.assignTags = TemplateBase.assignTags\nTemplate.removeTags = TemplateBase.removeTags\nTemplate.getTags = TemplateBase.getTags\nTemplate.toJSON = TemplateBase.toJSON\nTemplate.toDockerfile = TemplateBase.toDockerfile\n\nexport type {\n  BuildInfo,\n  BuildOptions,\n  BuildStatusReason,\n  CopyItem,\n  GetBuildStatusOptions,\n  McpServerName,\n  TemplateBuilder,\n  TemplateBuildStatus,\n  TemplateBuildStatusResponse,\n  TemplateClass,\n  TemplateTag,\n  TemplateTagInfo,\n} from './types'\n","export { ApiClient } from './api'\nexport type { components, paths } from './api'\n\nexport { ConnectionConfig } from './connectionConfig'\nexport type { ConnectionOpts, Username } from './connectionConfig'\nexport {\n  AuthenticationError,\n  FileNotFoundError,\n  GitAuthError,\n  GitUpstreamError,\n  InvalidArgumentError,\n  NotEnoughSpaceError,\n  NotFoundError,\n  SandboxError,\n  SandboxNotFoundError,\n  TemplateError,\n  TimeoutError,\n  RateLimitError,\n  BuildError,\n  FileUploadError,\n  VolumeError,\n} from './errors'\nexport type { Logger } from './logs'\n\nexport { getSignature } from './sandbox/signature'\n\nexport { FileType } from './sandbox/filesystem'\nexport type {\n  WriteInfo,\n  EntryInfo,\n  Filesystem,\n  FilesystemWriteOpts,\n  FilesystemReadOpts,\n} from './sandbox/filesystem'\nexport { FilesystemEventType } from './sandbox/filesystem/watchHandle'\nexport type {\n  FilesystemEvent,\n  WatchHandle,\n} from './sandbox/filesystem/watchHandle'\n\nexport { CommandExitError } from './sandbox/commands/commandHandle'\nexport type {\n  CommandResult,\n  Stdout,\n  Stderr,\n  PtyOutput,\n  CommandHandle,\n} from './sandbox/commands/commandHandle'\nexport type {\n  SandboxInfo,\n  SandboxMetrics,\n  SandboxOpts,\n  SandboxApiOpts,\n  SandboxConnectOpts,\n  SandboxMetricsOpts,\n  SandboxState,\n  SandboxListOpts,\n  SandboxPaginator,\n  SandboxNetworkOpts,\n  SandboxLifecycle,\n  SandboxInfoLifecycle,\n  SnapshotInfo,\n  SnapshotListOpts,\n  SnapshotPaginator,\n  CreateSnapshotOpts,\n} from './sandbox/sandboxApi'\n\nexport type { McpServer } from './sandbox/mcp'\n\nexport { ALL_TRAFFIC } from './sandbox/network'\n\nexport type {\n  ProcessInfo,\n  CommandRequestOpts,\n  CommandConnectOpts,\n  CommandStartOpts,\n  Commands,\n  Pty,\n} from './sandbox/commands'\n\nexport { Git } from './sandbox/git'\nexport type {\n  GitRequestOpts,\n  GitCloneOpts,\n  GitInitOpts,\n  GitRemoteAddOpts,\n  GitCommitOpts,\n  GitAddOpts,\n  GitDeleteBranchOpts,\n  GitPushOpts,\n  GitPullOpts,\n  GitDangerouslyAuthenticateOpts,\n  GitConfigOpts,\n  GitConfigScope,\n  GitBranches,\n  GitFileStatus,\n  GitStatus,\n} from './sandbox/git'\n\nexport { Volume, VolumeFileType } from './volume'\nexport type {\n  VolumeInfo,\n  VolumeAndToken,\n  VolumeEntryStat,\n  VolumeMetadataOptions,\n  VolumeWriteOptions,\n  VolumeApiOpts,\n  VolumeConnectionConfig,\n} from './volume'\n\nexport { Sandbox }\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n\nexport * from './template'\n\nexport {\n  ReadyCmd,\n  waitForPort,\n  waitForURL,\n  waitForProcess,\n  waitForFile,\n  waitForTimeout,\n} from './template/readycmd'\n\nexport {\n  LogEntry,\n  LogEntryStart,\n  LogEntryEnd,\n  type LogEntryLevel,\n  defaultBuildLogger,\n} from './template/logger'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,kBAAqC;;;ACA5C,OAAOA,eAAc;;;ACEnB,cAAW;;;ACFb,OAAO,cAAc;AAarB,SAAS,aAAoD;AAb7D,MAAAC,KAAA;AAeE,MAAK,WAAmB,KAAK;AAE3B,WAAO,EAAE,SAAS,OAAO,SAAS,WAAW,IAAI,QAAQ;AAAA,EAC3D;AAGA,MAAK,WAAmB,MAAM;AAE5B,WAAO,EAAE,SAAS,QAAQ,SAAS,WAAW,KAAK,QAAQ,KAAK;AAAA,EAClE;AAEA,QAAK,MAAAA,MAAA,WAAmB,YAAnB,gBAAAA,IAA4B,YAA5B,mBAAqC,UAAS,QAAQ;AACzD,WAAO,EAAE,SAAS,QAAQ,SAAS,SAAS,WAAW,UAAU;AAAA,EACnE;AAGA,MAAI,OAAO,gBAAgB,UAAU;AACnC,WAAO,EAAE,SAAS,eAAe,SAAS,UAAU;AAAA,EACtD;AAEA,QAAK,gBAAmB,cAAnB,mBAA8B,eAAc,sBAAsB;AACrE,WAAO,EAAE,SAAS,qBAAqB,SAAS,UAAU;AAAA,EAC5D;AAEA,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,EAAE,SAAS,WAAW,SAAS,SAAS,WAAW,UAAU;AAAA,EACtE;AAEA,SAAO,EAAE,SA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A,QAAI,KAAK,iBAAiB,QAAW;AACnC,mBAAa,eAAe,KAAK;AAAA,IACnC;AAEA,QAAI,KAAK,mBAAmB,QAAW;AACrC,mBAAa,oBAAoB,KAAK;AAAA,IACxC;AAEA,WAAO;AAAA,EACT;AACF;AAoBO,SAAS,SAAS,SAA8C;AACrE,SAAO,IAAI,aAAa,OAAO;AACjC;AAEA,SAAS,QAAQ,aAAa;AAC9B,SAAS,oBAAoB,aAAa;AAC1C,SAAS,iBAAiB,aAAa;AACvC,SAAS,SAAS,aAAa;AAC/B,SAAS,cAAc,aAAa;AACpC,SAAS,aAAa,aAAa;AACnC,SAAS,aAAa,aAAa;AACnC,SAAS,UAAU,aAAa;AAChC,SAAS,SAAS,aAAa;AAC/B,SAAS,eAAe,aAAa;;;AC9pCrC,IAAO,cAAQ;","names":["platform","_a","platform","_a","_a","_a","message","_a","path","Code","ConnectError","createClient","createClient","_a","createClient","Code","ConnectError","DEFAULT_ERROR_MAP","Code","ConnectError","FilesystemEventType","_a","compareVersions","Code","FileType","Filesystem","createClient","path","_a","compareVersions","ConnectError","_a","name","path","_a","path","fetch","paths","createClient","_a","createClient","VolumeFileType","_a","path","hasWarnedUndiciFallback","_a","warnUndiciFallback","Code","ConnectError","createClient","compareVersions","enumDesc","fileDesc","messageDesc","serviceDesc","serviceDesc","Code","ConnectError","createClient","createClient","_a","pid","ConnectError","Code","createClient","compareVersions","ConnectError","Code","_a","pid","compareVersions","_a","compareVersions","_b","compareVersions","_a","envdFetch","envdRpcFetch","Filesystem","path","compareVersions","crypto","_a","path","crypto","stats","content","_a","fs","fs","_a","_a","version","src","path","paths","_b","_c","_d"]}