tensorlake 0.5.127 → 0.5.129

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/defaults.ts","../src/errors.ts","../src/sdk-timings.ts","../src/http.ts","../src/models.ts","../src/sse.ts","../src/cloud-client.ts","../src/image.ts","../lib/libc.cjs","../src/native-binding.ts","../src/sandbox-image.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","declare const __SDK_VERSION__: string;\nexport const SDK_VERSION: string = __SDK_VERSION__;\n\nexport const API_URL =\n process.env.TENSORLAKE_API_URL ?? \"https://api.tensorlake.ai\";\nexport const API_KEY = process.env.TENSORLAKE_API_KEY ?? undefined;\nexport const NAMESPACE = process.env.INDEXIFY_NAMESPACE ?? \"default\";\nexport const SANDBOX_PROXY_URL =\n process.env.TENSORLAKE_SANDBOX_PROXY_URL ?? \"https://sandbox.tensorlake.ai\";\n\nexport const DEFAULT_HTTP_TIMEOUT_MS = 300_000;\nexport const MAX_RETRIES = 3;\nexport const RETRY_BACKOFF_MS = 500;\nexport const RETRYABLE_STATUS_CODES = new Set([429, 502, 503, 504]);\n","/** Base exception for all sandbox-related errors. */\nexport class SandboxException extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SandboxException\";\n }\n}\n\n/** General sandbox operation error. */\nexport class SandboxError extends SandboxException {\n constructor(message: string) {\n super(message);\n this.name = \"SandboxError\";\n }\n}\n\n/**\n * Raised when the client cannot complete a request against the API server.\n *\n * The original transport error (typically undici's `TypeError: fetch failed`,\n * whose real reason — `ECONNREFUSED`, `UND_ERR_CONNECT_TIMEOUT`, `EMFILE`, … —\n * lives in `.cause`) is preserved on this error's {@link cause} for programmatic\n * inspection, and its full chain is folded into the message so it survives\n * wrappers that only forward `error.message`. No interpretation of the failure\n * (client vs server) is applied — the raw inner error is surfaced as-is so the\n * reader can judge.\n */\nexport class SandboxConnectionError extends SandboxError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(`Connection error: ${message}`);\n this.name = \"SandboxConnectionError\";\n if (options?.cause !== undefined) this.cause = options.cause;\n }\n}\n\n/**\n * Flatten an error and its `cause` chain into a single readable line, appending\n * each level's `code` when it is not already present in the message. undici\n * reports `fetch failed` at the top and the real reason one or more levels down\n * in `.cause`, so this surfaces the part that actually identifies the failure.\n *\n * @example \"fetch failed: connect ECONNREFUSED 10.0.0.1:443\"\n * @example \"fetch failed: Connect Timeout Error (UND_ERR_CONNECT_TIMEOUT)\"\n */\nexport function describeError(err: unknown): string {\n const parts: string[] = [];\n const seen = new Set<unknown>();\n let current: unknown = err;\n\n for (let depth = 0; depth < 6; depth++) {\n if (current == null || typeof current !== \"object\" || seen.has(current)) {\n break;\n }\n seen.add(current);\n const e = current as { message?: unknown; code?: unknown; cause?: unknown };\n const message = typeof e.message === \"string\" ? e.message.trim() : \"\";\n const code = typeof e.code === \"string\" ? e.code : undefined;\n\n let segment = message;\n if (code && (!message || !message.includes(code))) {\n segment = segment ? `${segment} (${code})` : code;\n }\n if (segment && !parts.includes(segment)) parts.push(segment);\n\n current = e.cause;\n }\n\n if (parts.length > 0) return parts.join(\": \");\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Raised when a sandbox is not found. */\nexport class SandboxNotFoundError extends SandboxError {\n readonly sandboxId: string;\n\n constructor(sandboxId: string) {\n super(`Sandbox not found: ${sandboxId}`);\n this.name = \"SandboxNotFoundError\";\n this.sandboxId = sandboxId;\n }\n}\n\n/** Raised when a sandbox pool is not found. */\nexport class PoolNotFoundError extends SandboxError {\n readonly poolId: string;\n\n constructor(poolId: string) {\n super(`Sandbox pool not found: ${poolId}`);\n this.name = \"PoolNotFoundError\";\n this.poolId = poolId;\n }\n}\n\n/** Raised when attempting to delete a pool that is in use. */\nexport class PoolInUseError extends SandboxError {\n readonly poolId: string;\n\n constructor(poolId: string, message?: string) {\n const base = `Cannot delete pool ${poolId}: pool is in use`;\n super(message ? `${base} - ${message}` : base);\n this.name = \"PoolInUseError\";\n this.poolId = poolId;\n }\n}\n\n/** Raised when the remote API returns an error. */\nexport class RemoteAPIError extends SandboxError {\n readonly statusCode: number;\n readonly responseMessage: string;\n\n constructor(statusCode: number, message: string) {\n super(`API error (status ${statusCode}): ${message}`);\n this.name = \"RemoteAPIError\";\n this.statusCode = statusCode;\n this.responseMessage = message;\n }\n}\n\n/** Raised when request output is fetched before the request has completed. */\nexport class RequestNotFinishedError extends Error {\n constructor() {\n super(\"Request has not finished yet\");\n this.name = \"RequestNotFinishedError\";\n }\n}\n\n/** Raised when a request completed unsuccessfully. */\nexport class RequestFailedError extends Error {\n readonly failure: string;\n\n constructor(failure: string) {\n super(`Request failed: ${failure}`);\n this.name = \"RequestFailedError\";\n this.failure = failure;\n }\n}\n\n/** Raised when a request surfaced an application-level error. */\nexport class RequestExecutionError extends Error {\n readonly functionName?: string;\n\n constructor(message: string, functionName?: string) {\n super(\n functionName ? `Request error in ${functionName}: ${message}` : message,\n );\n this.name = \"RequestExecutionError\";\n this.functionName = functionName;\n }\n}\n","const SDK_TIMINGS_ENV_VAR = \"TENSORLAKE_SDK_TIMINGS\";\nconst SDK_TIMING_PAYLOADS_ENV_VAR = \"TENSORLAKE_SDK_TIMING_PAYLOADS\";\n\nexport type SdkTimingFields = Record<string, string | number | boolean | null | undefined>;\n\nexport function sdkTimingsEnabled(): boolean {\n const value = process.env[SDK_TIMINGS_ENV_VAR];\n return value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\nexport function sdkTimingPayloadsEnabled(): boolean {\n const value = process.env[SDK_TIMING_PAYLOADS_ENV_VAR];\n return value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\nexport function nowMs(): number {\n return performance.now();\n}\n\nexport function logSdkTiming(\n op: string,\n phase: string,\n startedAt: number,\n fields: SdkTimingFields = {},\n): void {\n if (!sdkTimingsEnabled()) return;\n logSdkTimingEvent(op, phase, {\n ...fields,\n duration_ms: Math.round((nowMs() - startedAt) * 100) / 100,\n });\n}\n\nexport function logSdkTimingEvent(\n op: string,\n phase: string,\n fields: SdkTimingFields = {},\n): void {\n if (!sdkTimingsEnabled()) return;\n\n const parts = [\n \"[tensorlake:sdk-timing]\",\n `op=${op}`,\n `phase=${phase}`,\n ];\n\n for (const [key, value] of Object.entries(fields)) {\n if (value == null) continue;\n parts.push(`${key}=${formatSdkTimingValue(value)}`);\n }\n\n console.error(parts.join(\" \"));\n}\n\nfunction formatSdkTimingValue(value: string | number | boolean): string {\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (/^[A-Za-z0-9_./:@-]+$/.test(value)) {\n return value;\n }\n return JSON.stringify(value);\n}\n","import {\n Agent,\n fetch as undiciFetch,\n setGlobalDispatcher,\n type BodyInit as UndiciBodyInit,\n} from \"undici\";\nimport * as defaults from \"./defaults.js\";\nimport {\n describeError,\n PoolInUseError,\n PoolNotFoundError,\n RemoteAPIError,\n SandboxConnectionError,\n SandboxNotFoundError,\n} from \"./errors.js\";\nimport {\n nowMs,\n logSdkTimingEvent,\n logSdkTiming,\n sdkTimingPayloadsEnabled,\n} from \"./sdk-timings.js\";\n\nconst REQUEST_TIMEOUT_HEADER = \"X-Tensorlake-Request-Timeout-Ms\";\n\nexport interface HttpClientOptions {\n baseUrl: string;\n apiKey?: string;\n organizationId?: string;\n projectId?: string;\n hostHeader?: string;\n sandboxIdHeader?: string;\n routingHint?: string;\n maxRetries?: number;\n retryBackoffMs?: number;\n timeoutMs?: number | null;\n}\n\nsetGlobalDispatcher(\n new Agent({\n keepAliveTimeout: 60_000,\n allowH2: true,\n }),\n);\n\n\ntype RequestBody = BodyInit | Uint8Array | ArrayBuffer;\n\nexport interface HttpRequestOptions {\n body?: RequestBody | null;\n headers?: Record<string, string>;\n json?: unknown;\n signal?: AbortSignal;\n allowHttpErrors?: boolean;\n retryableStatusCodes?: Set<number>;\n allowedErrorStatusCodes?: Set<number>;\n}\n\n/**\n * The return value of every SDK operation. Carries the W3C `trace_id` so callers\n * can correlate a specific request with its server-side spans in Datadog APM or\n * any other OTEL-compatible backend.\n *\n * Because this is an intersection type, all properties of `T` are accessible\n * directly — existing code that ignores `traceId` continues to compile and run\n * unchanged.\n *\n * @example\n * const sandbox = await client.createSandbox(req);\n * console.log(sandbox.id); // existing field — unchanged\n * console.log(sandbox.traceId); // new: look this up in Datadog APM\n */\nexport type Traced<T> = T & { readonly traceId: string };\n\nfunction withTraceId<T>(value: T, traceId: string): Traced<T> {\n if (value == null) {\n return { traceId } as unknown as Traced<T>;\n }\n return Object.assign(value as any, { traceId }) as Traced<T>;\n}\n\n/**\n * Internal HTTP client with retry logic, auth headers, and error mapping.\n *\n * Uses native `fetch`. Retries on transient status codes (429, 502, 503, 504)\n * with exponential backoff.\n */\nexport class HttpClient {\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n private readonly maxRetries: number;\n private readonly retryBackoffMs: number;\n private readonly timeoutMs: number | null;\n private abortController: AbortController | null = null;\n\n constructor(options: HttpClientOptions) {\n const url = options.baseUrl;\n this.baseUrl = url.endsWith(\"/\") ? url.slice(0, -1) : url;\n this.maxRetries = options.maxRetries ?? defaults.MAX_RETRIES;\n this.retryBackoffMs = options.retryBackoffMs ?? defaults.RETRY_BACKOFF_MS;\n this.timeoutMs = options.timeoutMs === undefined\n ? defaults.DEFAULT_HTTP_TIMEOUT_MS\n : options.timeoutMs;\n\n this.headers = {\n \"User-Agent\": `tensorlake-typescript-sdk/${defaults.SDK_VERSION}`,\n };\n if (this.timeoutMs != null) {\n this.headers[REQUEST_TIMEOUT_HEADER] = String(this.timeoutMs);\n }\n if (options.apiKey) {\n this.headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n if (options.organizationId) {\n this.headers[\"X-Forwarded-Organization-Id\"] = options.organizationId;\n }\n if (options.projectId) {\n this.headers[\"X-Forwarded-Project-Id\"] = options.projectId;\n }\n if (options.hostHeader) {\n this.headers[\"Host\"] = options.hostHeader;\n }\n if (options.sandboxIdHeader) {\n this.headers[\"X-Tensorlake-Sandbox-Id\"] = options.sandboxIdHeader;\n }\n if (options.routingHint) {\n this.headers[\"X-Tensorlake-Route-Hint\"] = options.routingHint;\n }\n }\n\n close(): void {\n this.abortController?.abort();\n this.abortController = null;\n }\n\n /** Make a JSON request, returning the parsed response body. */\n async requestJson<T>(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n retryableStatusCodes?: Set<number>;\n allowedErrorStatusCodes?: Set<number>;\n allowHttpErrors?: boolean;\n },\n ): Promise<Traced<T>> {\n const response = await this.requestResponse(method, path, {\n json: options?.body,\n headers: options?.headers,\n signal: options?.signal,\n retryableStatusCodes: options?.retryableStatusCodes,\n allowedErrorStatusCodes: options?.allowedErrorStatusCodes,\n allowHttpErrors: options?.allowHttpErrors,\n });\n const text = await response.text();\n const data = (text ? JSON.parse(text) : undefined) as T;\n return withTraceId(data, response.traceId);\n }\n\n /** Make a request returning raw bytes. */\n async requestBytes(\n method: string,\n path: string,\n options?: {\n body?: RequestBody | null;\n contentType?: string;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n },\n ): Promise<Traced<Uint8Array>> {\n const headers = { ...(options?.headers ?? {}) };\n if (options?.contentType) {\n headers[\"Content-Type\"] = options.contentType;\n }\n\n const response = await this.requestResponse(method, path, {\n body: options?.body,\n headers,\n signal: options?.signal,\n });\n const buffer = await response.arrayBuffer();\n return withTraceId(new Uint8Array(buffer), response.traceId);\n }\n\n /** Make a request and return the response body as an SSE stream. */\n async requestStream(\n method: string,\n path: string,\n options?: { signal?: AbortSignal; json?: unknown },\n ): Promise<Traced<ReadableStream<Uint8Array>>> {\n const response = await this.requestResponse(method, path, {\n json: options?.json,\n headers: { Accept: \"text/event-stream\" },\n signal: options?.signal,\n });\n if (!response.body) {\n throw new RemoteAPIError(\n response.status,\n \"No response body for SSE stream\",\n );\n }\n return withTraceId(response.body, response.traceId);\n }\n\n /** Make a request and return the raw Response. */\n async requestResponse(\n method: string,\n path: string,\n options?: HttpRequestOptions,\n ): Promise<Traced<Response>> {\n const headers = {\n ...this.headers,\n ...(options?.headers ?? {}),\n };\n const hasJsonBody = options?.json !== undefined;\n if (hasJsonBody && !hasHeader(headers, \"Content-Type\")) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n const body = hasJsonBody\n ? JSON.stringify(options?.json)\n : normalizeRequestBody(options?.body);\n\n const { response, traceId } = await this.doFetch(\n method,\n path,\n body,\n headers,\n options?.signal,\n options?.allowHttpErrors ?? false,\n options?.retryableStatusCodes ?? defaults.RETRYABLE_STATUS_CODES,\n options?.allowedErrorStatusCodes ?? new Set(),\n );\n return withTraceId(response, traceId);\n }\n\n private static makeTraceparent(): { traceparent: string; traceId: string } {\n const randomHex = (bytes: number) =>\n Array.from(crypto.getRandomValues(new Uint8Array(bytes)))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n const traceId = randomHex(16);\n const spanId = randomHex(8);\n return { traceparent: `00-${traceId}-${spanId}-01`, traceId };\n }\n\n private async doFetch(\n method: string,\n path: string,\n body: UndiciBodyInit | undefined,\n headers: Record<string, string>,\n signal?: AbortSignal,\n allowHttpErrors = false,\n retryableStatusCodes: Set<number> = defaults.RETRYABLE_STATUS_CODES,\n allowedErrorStatusCodes: Set<number> = new Set(),\n ): Promise<{ response: Response; traceId: string }> {\n const url = `${this.baseUrl}${path}`;\n const { traceparent, traceId } = HttpClient.makeTraceparent();\n headers[\"traceparent\"] = traceparent;\n let lastError: Error | undefined;\n const operationStart = nowMs();\n const timingPath = sdkTimingPayloadsEnabled() ? path : stripPathPayload(path);\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n if (attempt > 0) {\n const delay = this.retryBackoffMs * Math.pow(2, attempt - 1);\n logSdkTimingEvent(\"http.request\", \"retry_sleep_start\", {\n method,\n path: timingPath,\n attempt,\n delay_ms: delay,\n server_trace_id: traceId,\n });\n await sleep(delay);\n }\n\n this.abortController = new AbortController();\n // Track whether *our* deadline fired, so we can tell a client-imposed\n // timeout apart from a network rejection or a caller-initiated abort.\n let timedOut = false;\n const timeoutId = this.timeoutMs == null\n ? null\n : setTimeout(() => {\n timedOut = true;\n this.abortController?.abort();\n }, this.timeoutMs);\n\n // Combine external signal with internal timeout\n const combinedSignal = signal\n ? anySignal([signal, this.abortController.signal])\n : this.abortController.signal;\n\n const attemptStart = nowMs();\n try {\n const response = (await undiciFetch(url, {\n method,\n headers,\n body,\n signal: combinedSignal,\n })) as unknown as Response;\n\n if (timeoutId != null) clearTimeout(timeoutId);\n logSdkTiming(\"http.request\", \"headers\", attemptStart, {\n method,\n path: timingPath,\n status: response.status,\n attempt,\n server_trace_id: traceId,\n });\n\n if (response.ok) {\n logSdkTiming(\"http.request\", \"complete\", operationStart, {\n method,\n path: timingPath,\n status: response.status,\n attempts: attempt + 1,\n server_trace_id: traceId,\n });\n return { response, traceId };\n }\n\n // Check if retryable\n if (\n retryableStatusCodes.has(response.status) &&\n attempt < this.maxRetries\n ) {\n lastError = new RemoteAPIError(\n response.status,\n await response.text().catch(() => \"\"),\n );\n logSdkTimingEvent(\"http.request\", \"retryable_status\", {\n method,\n path: timingPath,\n status: response.status,\n attempt,\n server_trace_id: traceId,\n });\n continue;\n }\n\n if (allowHttpErrors || allowedErrorStatusCodes.has(response.status)) {\n logSdkTiming(\"http.request\", \"complete\", operationStart, {\n method,\n path: timingPath,\n status: response.status,\n attempts: attempt + 1,\n server_trace_id: traceId,\n });\n return { response, traceId };\n }\n\n // Non-retryable error — throw mapped error\n const errorBody = await response.text().catch(() => \"\");\n throwMappedError(response.status, errorBody, path);\n } catch (err) {\n if (timeoutId != null) clearTimeout(timeoutId);\n\n if (\n err instanceof RemoteAPIError ||\n err instanceof SandboxNotFoundError ||\n err instanceof PoolNotFoundError ||\n err instanceof PoolInUseError\n ) {\n throw err;\n }\n\n // A caller-supplied signal fired (and it wasn't our own deadline).\n if (signal?.aborted && !timedOut) {\n throw new SandboxConnectionError(\"request aborted by caller\", {\n cause: err,\n });\n }\n\n // Network / timeout error\n lastError = err instanceof Error ? err : new Error(String(err));\n logSdkTiming(\"http.request\", \"error\", attemptStart, {\n method,\n path: timingPath,\n attempt,\n server_trace_id: traceId,\n error: timedOut ? `request timed out after ${this.timeoutMs}ms` : describeError(err),\n });\n\n if (attempt >= this.maxRetries) {\n // Surface the real inner cause; for our own deadline, say so plainly.\n const detail = timedOut\n ? `request timed out after ${this.timeoutMs}ms`\n : describeError(err);\n throw new SandboxConnectionError(detail, { cause: err });\n }\n }\n }\n\n throw new SandboxConnectionError(\n lastError ? describeError(lastError) : \"request failed\",\n { cause: lastError },\n );\n }\n}\n\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n const lowered = name.toLowerCase();\n return Object.keys(headers).some((key) => key.toLowerCase() === lowered);\n}\n\nfunction normalizeRequestBody(\n body?: RequestBody | null,\n): UndiciBodyInit | undefined {\n if (body == null) {\n return undefined;\n }\n if (body instanceof Uint8Array) {\n return Uint8Array.from(body).buffer as ArrayBuffer;\n }\n return body as UndiciBodyInit;\n}\n\nfunction stripPathPayload(path: string): string {\n const queryStart = path.search(/[?#]/);\n return queryStart === -1 ? path : path.slice(0, queryStart);\n}\n\n/** Map HTTP status codes to specific error types. */\nfunction throwMappedError(status: number, body: string, path: string): never {\n let message = body;\n try {\n const parsed = JSON.parse(body);\n if (parsed.message) message = parsed.message;\n else if (parsed.error) message = parsed.error;\n } catch {\n // use raw body\n }\n\n if (status === 404) {\n // Determine entity type from path\n if (path.includes(\"sandbox-pools\") || path.includes(\"pools\")) {\n const match = path.match(/sandbox-pools\\/([^/]+)/);\n if (match) throw new PoolNotFoundError(match[1]);\n }\n if (path.includes(\"sandboxes\")) {\n const match = path.match(/sandboxes\\/([^/]+)/);\n if (match) throw new SandboxNotFoundError(match[1]);\n }\n throw new RemoteAPIError(404, message);\n }\n\n if (status === 409) {\n if (path.includes(\"sandbox-pools\") || path.includes(\"pools\")) {\n const match = path.match(/sandbox-pools\\/([^/]+)/);\n if (match) throw new PoolInUseError(match[1], message);\n }\n }\n\n throw new RemoteAPIError(status, message);\n}\n\n/** Combine multiple AbortSignals into one that aborts when any fires. */\nfunction anySignal(signals: AbortSignal[]): AbortSignal {\n const controller = new AbortController();\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n return controller.signal;\n }\n signal.addEventListener(\"abort\", () => controller.abort(signal.reason), {\n once: true,\n });\n }\n return controller.signal;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","// --- Enums ---\n\nexport enum SandboxStatus {\n PENDING = \"pending\",\n RUNNING = \"running\",\n SNAPSHOTTING = \"snapshotting\",\n SUSPENDING = \"suspending\",\n SUSPENDED = \"suspended\",\n TERMINATED = \"terminated\",\n TIMEOUT = \"timeout\",\n}\n\nexport enum SnapshotStatus {\n IN_PROGRESS = \"in_progress\",\n LOCAL_READY = \"local_ready\",\n COMPLETED = \"completed\",\n FAILED = \"failed\",\n}\n\n/**\n * Snapshot type for sandbox snapshot creation.\n *\n * - `\"memory\"`: Capture VM memory + filesystem state. Sandboxes restored\n * from this snapshot warm-restore VM memory.\n * - `\"filesystem\"`: Capture filesystem state only. Sandboxes restored from\n * this snapshot cold-boot from the snapshot tarball instead of warm-\n * restoring VM state. Use this for sandbox image builds so that the\n * restored sandbox bypasses Firecracker's overlay-path constraints.\n */\nexport type SnapshotType = \"memory\" | \"filesystem\";\n\n/**\n * Checkpoint type for {@link Sandbox.checkpoint}.\n *\n * - `\"memory\"`: Capture VM memory + filesystem state. Sandboxes restored\n * from this checkpoint warm-restore VM memory and running processes.\n * - `\"filesystem\"`: Capture filesystem state only. Sandboxes restored from\n * this checkpoint cold-boot from the snapshot tarball.\n */\nexport type CheckpointType = \"memory\" | \"filesystem\";\n\nexport type SnapshotWaitCondition = \"local_ready\" | \"completed\";\n\nexport enum ProcessStatus {\n RUNNING = \"running\",\n EXITED = \"exited\",\n SIGNALED = \"signaled\",\n OOM_KILLED = \"oom_killed\",\n}\n\nexport enum StdinMode {\n CLOSED = \"closed\",\n PIPE = \"pipe\",\n}\n\nexport enum OutputMode {\n CAPTURE = \"capture\",\n DISCARD = \"discard\",\n}\n\nexport enum ContainerState {\n IDLE = \"Idle\",\n RUNNING = \"Running\",\n}\n\n// --- Resource / Network ---\n\nexport interface ContainerResourcesInfo {\n cpus: number;\n memoryMb: number;\n ephemeralDiskMb: number;\n}\n\n/** GPU models supported by the sandbox scheduler. */\nexport type GpuModel =\n | \"A100-40GB\"\n | \"A100-80GB\"\n | \"H100\"\n | \"T4\"\n | \"A6000\"\n | \"A10\";\n\n/** A homogeneous GPU allocation for a sandbox. */\nexport interface GpuRequest {\n count: number;\n model: GpuModel;\n}\n\nexport interface GPUResources {\n count: number;\n model: string;\n}\n\n/**\n * Egress network access control policy for a sandbox.\n *\n * `denyOut` takes precedence over `allowOut`: a destination matched by both is\n * blocked. Entries may be IPv4 addresses, CIDR ranges, or DNS hostnames;\n * hostname rules are followed across DNS changes. The policy can be changed on\n * a running sandbox via `Sandbox.update({ network })` (pass `null` to clear).\n */\nexport interface NetworkConfig {\n allowInternetAccess: boolean;\n allowOut: string[];\n denyOut: string[];\n}\n\n/**\n * One file system mounted into a sandbox at an absolute guest path.\n *\n * `fileSystemId` is the Artifact Storage file-system name created with\n * `tl fs create <name>` and `mountPath` is an absolute, unique guest path\n * (e.g. `/mnt/skills`).\n *\n * `readOnly` and `prefetch` are optional mount modes; they are sent on the\n * wire only when `true` (older servers reject unknown mount fields, so\n * `false` is expressed by omission).\n *\n * `snapshotId` pins the mount to a specific filesystem snapshot. A pinned\n * mount must also set `readOnly: true` (the server rejects a writable pin\n * with HTTP 400). It is sent only when set, for the same compatibility\n * reason as the mount modes.\n *\n * `owner` presents the mounted files as owned by a guest user: `NAME`,\n * `UID`, `NAME:GROUP`, or `UID:GID` (e.g. `\"agent\"` or `\"1001:1001\"`),\n * resolved against the sandbox image's own user database when the mount\n * attaches. Unset keeps the image default (the baked `tl-user` account when\n * the image has one, otherwise root). It is sent only when set, for the\n * same compatibility reason as the mount modes.\n */\nexport interface FileSystemMount {\n fileSystemId: string;\n mountPath: string;\n /** Mount the file system read-only. */\n readOnly?: boolean;\n /** Eagerly download the file system's contents. */\n prefetch?: boolean;\n /** Pin the mount to a specific filesystem snapshot (requires `readOnly`). */\n snapshotId?: string;\n /** Present the mounted files as owned by this guest user spec. */\n owner?: string;\n}\n\n/** Optional mount modes for attaching a file system to a running sandbox. */\nexport interface AttachFileSystemOptions {\n /** Mount the file system read-only. */\n readOnly?: boolean;\n /** Eagerly download the file system's contents. */\n prefetch?: boolean;\n /** Pin the mount to a specific filesystem snapshot (requires `readOnly`). */\n snapshotId?: string;\n /** Present the mounted files as owned by this guest user spec. */\n owner?: string;\n}\n\nexport interface ClaimSandboxOptions {\n /** File systems to mount before the claimed sandbox is reported as running. */\n fileSystems?: FileSystemMount[];\n}\n\n// --- Sandbox lifecycle ---\n\nexport interface CreateSandboxOptions {\n /** Optional sandbox image name. GPU sandboxes require a CAS image; when omitted with a GPU request, Tensorlake uses the server's configured GPU default. */\n image?: string;\n /** CPU count. Defaults to 1 for fresh creates; snapshot restores inherit it when omitted. */\n cpus?: number;\n /** Memory in MB. Defaults to 1024 for fresh creates; snapshot restores inherit it when omitted. */\n memoryMb?: number;\n /** Root disk size in megabytes. When omitted, the server uses its default disk size. */\n diskMb?: number;\n /** Number of GPUs to allocate. Defaults to A10 unless gpuModel is set. GPU sandboxes require a CAS image. */\n gpus?: number;\n /** GPU model to allocate. The string arm preserves compatibility with existing callers; values are validated at runtime. */\n gpuModel?: GpuModel | (string & {});\n /** Typed GPU model and count request. Cannot be combined with gpus or gpuModel. */\n gpu?: GpuRequest;\n timeoutSecs?: number;\n entrypoint?: string[];\n allowInternetAccess?: boolean;\n allowOut?: string[];\n denyOut?: string[];\n snapshotId?: string;\n /** Optional name for the sandbox. Named sandboxes support suspend/resume. When absent the sandbox is ephemeral. */\n name?: string;\n /** File systems to mount on fresh creation or warm-pool claim, each at its own absolute, unique guest mount path. */\n fileSystems?: FileSystemMount[];\n}\n\nexport interface UpdateSandboxOptions {\n /** New name for the sandbox. Naming an ephemeral sandbox enables suspend/resume. */\n name?: string;\n /** Whether exposed user ports should be reachable without TensorLake auth. */\n allowUnauthenticatedAccess?: boolean;\n /** User ports that should be routable through the sandbox proxy. Port 9501 is reserved. */\n exposedPorts?: number[];\n /**\n * Egress network policy for the running sandbox, applied to the live VM's\n * firewall in one atomic swap. Omit to keep the current policy, set to\n * replace it, or pass `null` to clear it to unrestricted egress.\n */\n network?: NetworkConfig | null;\n}\n\nexport interface CreateSandboxResponse {\n sandboxId: string;\n status: SandboxStatus;\n reason?: string;\n routingHint?: string;\n ingressEndpoint?: string;\n sandboxUrl?: string;\n name?: string | null;\n terminationReason?: string;\n errorDetails?: unknown;\n}\n\nexport interface CopySandboxOptions {\n /** Number of running copies to create. Defaults to 1. */\n times?: number;\n /** Per-request timeout in seconds for the blocking live-copy request. */\n requestTimeout?: number;\n}\n\nexport interface CopiedSandboxResponse {\n sandboxId: string;\n /** Raw server status. Partial copy responses can include statuses such as `\"failed\"`. */\n status: string;\n reason?: string;\n routingHint?: string;\n ingressEndpoint?: string;\n sandboxUrl?: string;\n name?: string | null;\n terminationReason?: string;\n errorDetails?: unknown;\n}\n\nexport interface CopySandboxResponse {\n sourceSandboxId: string;\n sandboxes: CopiedSandboxResponse[];\n}\n\nexport interface SandboxInfo {\n sandboxId: string;\n namespace: string;\n status: SandboxStatus;\n /** Resolved sandbox image name. */\n image?: string;\n resources: ContainerResourcesInfo;\n timeoutSecs?: number;\n entrypoint?: string[];\n network?: NetworkConfig;\n poolId?: string;\n outcome?: string;\n terminationReason?: string;\n errorDetails?: unknown;\n createdAt?: Date;\n terminatedAt?: Date;\n name?: string;\n allowUnauthenticatedAccess?: boolean;\n exposedPorts?: number[];\n ingressEndpoint?: string;\n sandboxUrl?: string;\n routingHint?: string;\n /** File systems currently mounted into the sandbox, each at its own guest mount path. Empty when none are mounted. */\n fileSystems?: FileSystemMount[];\n}\n\nexport interface SandboxPortAccess {\n allowUnauthenticatedAccess: boolean;\n exposedPorts: number[];\n ingressEndpoint?: string;\n sandboxUrl?: string;\n}\n\n/** Sandbox information plus the archival timestamp. */\nexport interface ArchivedSandboxInfo extends SandboxInfo {\n archivedAt: Date;\n}\n\n/** Pagination params for `listArchivedSandboxes`. */\nexport interface ListArchivedSandboxesOptions {\n limit?: number;\n /** Base64-encoded pagination cursor returned by a prior call. */\n cursor?: string;\n /** Pagination direction. */\n direction?: \"forward\" | \"backward\";\n}\n\nexport interface ListArchivedSandboxesResponse {\n sandboxes: ArchivedSandboxInfo[];\n prevCursor?: string;\n nextCursor?: string;\n}\n\n// --- Snapshots ---\n\nexport interface CreateSnapshotResponse {\n snapshotId: string;\n status: SnapshotStatus;\n}\n\nexport interface SnapshotInfo {\n snapshotId: string;\n namespace: string;\n sandboxId: string;\n baseImage: string;\n status: SnapshotStatus;\n snapshotType?: SnapshotType;\n error?: string;\n snapshotUri?: string;\n snapshotFormatVersion?: string;\n sizeBytes?: number;\n rootfsDiskBytes?: number;\n createdAt?: Date;\n}\n\nexport interface SnapshotOptions {\n /**\n * Optional snapshot type. When omitted the server picks its default. Use\n * `\"filesystem\"` for snapshots intended for sandbox image builds so that\n * restored sandboxes cold-boot.\n */\n snapshotType?: SnapshotType;\n}\n\nexport interface SnapshotAndWaitOptions extends SnapshotOptions {\n timeout?: number;\n pollInterval?: number;\n /** Defaults to `\"local_ready\"`, which is enough to resume from a snapshot. */\n waitUntil?: SnapshotWaitCondition;\n}\n\n// --- Persisted sandbox logs ---\n\nexport type SandboxLogLevel =\n \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\" | \"fatal\";\n\nexport interface GetSandboxLogsOptions {\n levels?: SandboxLogLevel[];\n processIds?: string[];\n nextToken?: string;\n head?: number;\n tail?: number;\n body?: string;\n}\n\nexport interface SandboxLogSignal {\n timestamp: number;\n uuid: string;\n namespace: string;\n application: string;\n sandboxId?: string;\n resourceAttributes: Array<[string, string]>;\n body: string;\n logAttributes: string;\n allocations?: string[];\n functionRuns?: string[];\n level?: number;\n retention?: number;\n}\n\nexport interface SandboxLogsResponse {\n logs: SandboxLogSignal[];\n nextToken?: string;\n}\n\nexport interface SandboxProcessLogFilter {\n processId: string;\n processPid: string;\n processCommand: string;\n processManagedId: string;\n processManagedName: string;\n firstSeen: number;\n lastSeen: number;\n logCount: number;\n}\n\nexport interface SandboxProcessLogFiltersResponse {\n processes: SandboxProcessLogFilter[];\n}\n\n// --- Pools ---\n\nexport interface CreatePoolOptions {\n /** Sandbox image name, such as `tensorlake/ubuntu-minimal` or a registered Sandbox Image. */\n image: string;\n cpus?: number;\n memoryMb?: number;\n ephemeralDiskMb?: number;\n timeoutSecs?: number;\n entrypoint?: string[];\n maxContainers?: number;\n warmContainers?: number;\n /** Network policy for each container. Can be replaced later via updatePool. */\n network?: NetworkConfig;\n}\n\nexport interface UpdatePoolOptions {\n /**\n * Network policy for each container. Omit to keep the pool's current policy,\n * set to replace it, or pass `null` to remove it (unclaimed warm containers\n * are recycled onto the new policy).\n */\n network?: NetworkConfig | null;\n /** Sandbox image name, such as `tensorlake/ubuntu-minimal` or a registered Sandbox Image. */\n image: string;\n cpus?: number;\n memoryMb?: number;\n ephemeralDiskMb?: number;\n timeoutSecs?: number;\n entrypoint?: string[];\n maxContainers?: number;\n warmContainers?: number;\n}\n\nexport interface CreateSandboxPoolResponse {\n poolId: string;\n namespace: string;\n}\n\nexport interface PoolContainerInfo {\n id: string;\n state: string;\n sandboxId?: string;\n executorId: string;\n}\n\nexport interface SandboxPoolInfo {\n poolId: string;\n namespace: string;\n /** Sandbox image name backing the pool. */\n image: string;\n resources: ContainerResourcesInfo;\n timeoutSecs: number;\n entrypoint?: string[];\n maxContainers?: number;\n warmContainers?: number;\n /** The network policy that applies to each container in the pool. */\n networkPolicy?: NetworkConfig;\n containers?: PoolContainerInfo[];\n createdAt?: Date;\n updatedAt?: Date;\n}\n\n// --- Process management ---\n\nexport interface ProcessUserSpec {\n name?: string;\n uid?: number;\n gid?: number;\n}\n\nexport type ProcessUser = string | ProcessUserSpec;\n\nexport type RestartPolicy = \"never\" | \"on_failure\" | \"always\";\n\nexport interface RestartPolicyConfig {\n policy?: RestartPolicy;\n maxRestarts?: number;\n initialBackoffMs?: number;\n maxBackoffMs?: number;\n}\n\nexport type ProcessHealthCheckType = \"http\" | \"tcp\";\n\nexport interface ProcessHealthCheck {\n type: ProcessHealthCheckType;\n port: number;\n path?: string;\n initialDelayMs?: number;\n intervalMs?: number;\n timeoutMs?: number;\n failureThreshold?: number;\n}\n\nexport type ManagedProcessStatus =\n \"starting\" | \"running\" | \"backing_off\" | \"stopped\";\n\nexport type ManagedProcessHealthStatus =\n \"disabled\" | \"starting\" | \"healthy\" | \"unhealthy\";\n\nexport interface ManagedProcessExit {\n exitCode?: number;\n signal?: number;\n oomKilled: boolean;\n endedAt: Date;\n}\n\n/**\n * Managed-process metadata embedded into {@link ProcessInfo}.\n *\n * A managed process is addressable by either its current PID or, if a `name` was given at\n * creation, that name (process APIs accept a PID or process name). `id` is a stable\n * daemon-local identifier: it equals `name` when one was set, otherwise a daemon-assigned\n * opaque id (the process is then addressable only by PID, not by `id`).\n */\nexport interface ManagedProcessInfo {\n id: string;\n name?: string;\n status: ManagedProcessStatus;\n restartCount: number;\n restart: RestartPolicyConfig;\n healthCheck?: ProcessHealthCheck;\n healthStatus: ManagedProcessHealthStatus;\n consecutiveHealthFailures: number;\n lastExit?: ManagedProcessExit;\n lastError?: string;\n nextRestartAt?: Date;\n}\n\nexport interface StartProcessOptions {\n args?: string[];\n env?: Record<string, string>;\n workingDir?: string;\n stdinMode?: StdinMode;\n stdoutMode?: OutputMode;\n stderrMode?: OutputMode;\n user?: ProcessUser;\n /**\n * Optional managed-process name. Supplying this opts into managed process behavior, and\n * lets the process be addressed by this name (in addition to its PID) in\n * `getProcess`/`killProcess`/`sendSignal`/etc. — useful because a managed process's PID\n * changes when it restarts. May contain any characters except `/` and must not be all\n * digits (numeric strings are reserved for PID addressing). If omitted, the daemon assigns\n * an opaque id (`ManagedProcessInfo.id`) and the process is addressable only by its current PID.\n */\n name?: string;\n /** Optional restart behavior. Supplying this opts into managed process behavior. */\n restart?: RestartPolicyConfig;\n /** Optional HTTP/TCP health check. Supplying this opts into managed process behavior. */\n healthCheck?: ProcessHealthCheck;\n}\n\nexport interface ProcessInfo {\n handle?: number;\n pid: number;\n status: ProcessStatus;\n exitCode?: number;\n signal?: number;\n stdinWritable: boolean;\n command: string;\n args: string[];\n startedAt: Date;\n endedAt?: Date;\n managed?: ManagedProcessInfo;\n}\n\nexport interface SendSignalResponse {\n success: boolean;\n}\n\nexport interface OutputResponse {\n pid: number;\n lines: string[];\n lineCount: number;\n}\n\nexport interface OutputEvent {\n line: string;\n timestamp: Date;\n stream?: string;\n}\n\n// --- Run ---\n\nexport interface RunOptions {\n args?: string[];\n env?: Record<string, string>;\n workingDir?: string;\n timeout?: number;\n user?: ProcessUser;\n}\n\nexport interface CommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n// --- File operations ---\n\nexport interface DirectoryEntry {\n name: string;\n isDir: boolean;\n size?: number;\n modifiedAt?: Date;\n}\n\nexport interface ListDirectoryResponse {\n path: string;\n entries: DirectoryEntry[];\n}\n\n// --- PTY ---\n\nexport interface CreatePtySessionOptions {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n workingDir?: string;\n rows?: number;\n cols?: number;\n}\n\nexport interface PtySessionInfo {\n sessionId: string;\n token: string;\n}\n\n// --- Health ---\n\nexport interface HealthResponse {\n healthy: boolean;\n}\n\nexport interface DaemonInfo {\n version: string;\n uptimeSecs: number;\n runningProcesses: number;\n totalProcesses: number;\n}\n\n// --- Client options ---\n\nexport interface SandboxClientOptions {\n apiUrl?: string;\n apiKey?: string;\n organizationId?: string;\n projectId?: string;\n namespace?: string;\n maxRetries?: number;\n retryBackoffMs?: number;\n /** Total HTTP request timeout in seconds. Default: 300. */\n requestTimeout?: number;\n /** @deprecated Use requestTimeout. Total HTTP request timeout in milliseconds. */\n timeoutMs?: number;\n}\n\nexport interface SandboxOptions {\n sandboxId: string;\n /**\n * Explicit sandbox proxy base URL. Direct `new Sandbox(...)` construction\n * requires this; `Sandbox.connect()` and `SandboxClient.connect()` normally\n * resolve the server-returned `sandboxUrl`.\n */\n proxyUrl?: string;\n /** @internal Real caller/env proxy override, distinct from an internally selected proxyUrl. */\n explicitProxyUrl?: string;\n apiKey?: string;\n organizationId?: string;\n projectId?: string;\n routingHint?: string;\n resolveProxyInfo?: (\n identifier: string,\n ) => Promise<SandboxInfo & { readonly traceId: string }>;\n /** Optional total HTTP request timeout in seconds for sandbox proxy operations. Omit for no total proxy timeout. */\n requestTimeout?: number;\n /** @deprecated Use requestTimeout. Optional total HTTP request timeout in milliseconds for sandbox proxy operations. */\n timeoutMs?: number;\n /**\n * @internal Shared Rust-backed lifecycle client. When provided, the proxy\n * client is minted via `connectProxy` so it reuses this client's connection\n * pool (HTTP/2 coalescing across sandboxes).\n */\n nativeClient?: import(\"./native-sandbox.js\").NativeSandboxClient;\n}\n\nexport interface CreateAndConnectOptions extends CreateSandboxOptions {\n poolId?: string;\n proxyUrl?: string;\n /** Total HTTP request timeout in seconds for sandbox startup. Default: client requestTimeout. */\n requestTimeout?: number;\n /** @deprecated Use requestTimeout. */\n startupTimeout?: number;\n}\n\n/**\n * Options for `Sandbox.getOrCreate`: everything `create` accepts (used only\n * when a new sandbox must be created; `name` comes from the first argument),\n * plus `resume`. `poolId` is excluded: a pool claim cannot carry a name, so\n * a claimed sandbox could never be found again by a later call.\n */\nexport interface GetOrCreateOptions\n extends Omit<CreateAndConnectOptions, \"name\" | \"poolId\"> {\n /** Resume a suspended sandbox before returning. Default: true. */\n resume?: boolean;\n}\n\n/**\n * What `Sandbox.getOrCreate` did to bind the name, exposed as\n * `sandbox.bindOutcome`:\n *\n * - `\"created\"`: nothing held the name; the call created a new sandbox.\n * - `\"attached\"`: a sandbox already held the name and needed no resume.\n * Includes a sandbox that was still starting (the call waited for it)\n * and a suspended sandbox when `resume: false`.\n * - `\"resumed\"`: the sandbox was suspended when the call found it and is\n * running now.\n */\nexport type GetOrCreateOutcome = \"created\" | \"attached\" | \"resumed\";\n\nexport interface SuspendResumeOptions {\n /** If false, fire-and-return without waiting for completion. Default: true. */\n wait?: boolean;\n /** Max seconds to wait when wait=true. Default: 300. */\n timeout?: number;\n /** Seconds between status polls when wait=true. Default: 1. */\n pollInterval?: number;\n}\n\nexport interface CheckpointOptions extends SuspendResumeOptions {\n checkpointType?: CheckpointType;\n /** Defaults to `\"local_ready\"`, which is enough to resume from a checkpoint. */\n waitUntil?: SnapshotWaitCondition;\n}\n\nexport interface ConnectOptions {\n sandboxId: string;\n proxyUrl?: string;\n routingHint?: string;\n}\n\n// --- JSON key conversion helpers ---\n\nconst CAMEL_TO_SNAKE_RE = /[A-Z]/g;\n\n/** Convert a camelCase string to snake_case. */\nexport function camelToSnake(str: string): string {\n return str.replace(CAMEL_TO_SNAKE_RE, (ch) => \"_\" + ch.toLowerCase());\n}\n\n/** Convert a snake_case string to camelCase. */\nexport function snakeToCamel(str: string): string {\n return str.replace(/_([a-z])/g, (_, ch) => ch.toUpperCase());\n}\n\n/** Recursively convert all object keys from camelCase to snake_case. */\nexport function toSnakeKeys(obj: unknown): unknown {\n if (Array.isArray(obj)) return obj.map(toSnakeKeys);\n if (obj !== null && typeof obj === \"object\" && !(obj instanceof Date)) {\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n result[camelToSnake(k)] = toSnakeKeys(v);\n }\n return result;\n }\n return obj;\n}\n\n/**\n * Parse a numeric timestamp into a Date.\n *\n * Handles seconds, milliseconds, and microseconds by checking magnitude.\n */\nexport function parseTimestamp(v: unknown): Date | undefined {\n if (v == null) return undefined;\n if (v instanceof Date) return v;\n if (typeof v === \"string\") {\n const parsed = Date.parse(v);\n return Number.isNaN(parsed) ? undefined : new Date(parsed);\n }\n const ts = Number(v);\n if (isNaN(ts)) return undefined;\n if (ts > 1e15) return new Date(ts / 1000); // microseconds → ms\n if (ts > 1e12) return new Date(ts); // already ms\n return new Date(ts * 1000); // seconds → ms\n}\n\n/**\n * Recursively convert all object keys from snake_case to camelCase,\n * with special handling for `id` → contextual name and timestamp parsing.\n */\nexport function fromSnakeKeys(obj: unknown, idField?: string): unknown {\n if (Array.isArray(obj))\n return obj.map((item) => fromSnakeKeys(item, idField));\n if (obj !== null && typeof obj === \"object\" && !(obj instanceof Date)) {\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n let key: string;\n if (k === \"id\" && idField) {\n key = idField;\n } else {\n key = snakeToCamel(k);\n }\n\n // Parse timestamp fields\n if (\n key.endsWith(\"At\") ||\n key === \"timestamp\" ||\n key === \"startedAt\" ||\n key === \"endedAt\"\n ) {\n result[key] = parseTimestamp(v);\n } else if (typeof v === \"object\" && v !== null && !Array.isArray(v)) {\n result[key] = fromSnakeKeys(v);\n } else if (Array.isArray(v)) {\n result[key] = v.map((item) => fromSnakeKeys(item));\n } else {\n // Normalize null → undefined so optional fields match TypeScript's ? convention.\n result[key] = v === null ? undefined : v;\n }\n }\n return result;\n }\n return obj;\n}\n","export interface SSEMessage {\n data: string;\n event?: string;\n id?: string;\n}\n\n/**\n * Parse a Server-Sent Events stream into raw SSE messages.\n */\nexport async function* parseSSEMessages(\n stream: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncIterable<SSEMessage> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n if (signal?.aborted) break;\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(/\\r?\\n\\r?\\n/);\n buffer = parts.pop() ?? \"\";\n\n for (const part of parts) {\n const lines = part.split(/\\r?\\n/);\n const dataLines: string[] = [];\n let event: string | undefined;\n let id: string | undefined;\n\n for (const line of lines) {\n if (!line || line.startsWith(\":\")) continue;\n\n const separator = line.indexOf(\":\");\n const field = separator === -1 ? line : line.slice(0, separator);\n let value = separator === -1 ? \"\" : line.slice(separator + 1);\n if (value.startsWith(\" \")) {\n value = value.slice(1);\n }\n\n if (field === \"data\") {\n dataLines.push(value);\n } else if (field === \"event\") {\n event = value;\n } else if (field === \"id\") {\n id = value;\n }\n }\n\n if (dataLines.length > 0 || event || id) {\n yield { data: dataLines.join(\"\\n\"), event, id };\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Parse a Server-Sent Events stream from a ReadableStream<Uint8Array>.\n *\n * Yields parsed JSON objects for each `data:` line. Handles reconnection\n * by simply yielding events as they arrive.\n */\nexport async function* parseSSEStream<T>(\n stream: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncIterable<T> {\n for await (const message of parseSSEMessages(stream, signal)) {\n if (!message.data) continue;\n try {\n yield JSON.parse(message.data) as T;\n } catch {\n // Skip malformed JSON\n }\n }\n}\n","import { nanoid } from \"nanoid\";\n\nimport * as defaults from \"./defaults.js\";\nimport { HttpClient } from \"./http.js\";\nimport { fromSnakeKeys } from \"./models.js\";\nimport { parseSSEStream } from \"./sse.js\";\nimport type {\n ApplicationBuildContext,\n ApplicationBuildResponse,\n ApplicationManifest,\n ApplicationSummary,\n BinaryPayload,\n BuildInfo,\n BuildLogEntry,\n CloudClientOptions,\n CreateApplicationBuildRequest,\n NewSecret,\n RequestInput,\n RequestMetadata,\n RequestOutput,\n SandboxTemplate,\n Secret,\n SecretsList,\n StartImageBuildRequest,\n UpsertSecretResponse,\n} from \"./cloud-models.js\";\n\nexport class CloudClient {\n private readonly http: HttpClient;\n private readonly organizationId?: string;\n private readonly projectId?: string;\n private readonly namespace: string;\n\n constructor(options?: CloudClientOptions) {\n this.organizationId = options?.organizationId;\n this.projectId = options?.projectId;\n this.namespace = options?.namespace ?? defaults.NAMESPACE;\n this.http = new HttpClient({\n baseUrl: options?.apiUrl ?? defaults.API_URL,\n apiKey: options?.apiKey ?? defaults.API_KEY,\n organizationId: this.organizationId,\n projectId: this.projectId,\n maxRetries: options?.maxRetries ?? defaults.MAX_RETRIES,\n retryBackoffMs: options?.retryBackoffMs ?? defaults.RETRY_BACKOFF_MS,\n });\n }\n\n static forCloud(options?: CloudClientOptions): CloudClient {\n return new CloudClient(options);\n }\n\n close(): void {\n this.http.close();\n }\n\n async upsertApplication(\n manifest: ApplicationManifest,\n codeZip: BinaryPayload,\n upgradeRunningRequests = false,\n ): Promise<void> {\n const applicationManifest = { ...manifest };\n let publicEndpointId = publicEndpointIdFromManifest(applicationManifest);\n if (\n applicationAllowsUnauthenticatedRequests(applicationManifest) &&\n publicEndpointId === undefined\n ) {\n const applicationName = applicationManifest.name;\n if (typeof applicationName === \"string\" && applicationName.length > 0) {\n publicEndpointId =\n await this.existingApplicationPublicEndpointId(applicationName);\n }\n publicEndpointId ??= generatePublicEndpointId();\n }\n if (publicEndpointId !== undefined) {\n applicationManifest.public_endpoint_id = publicEndpointId;\n delete applicationManifest.publicEndpointId;\n }\n\n const form = new FormData();\n form.append(\n \"code\",\n new Blob([toBlobPart(codeZip)], { type: \"application/zip\" }),\n \"code.zip\",\n );\n form.append(\"code_content_type\", \"application/zip\");\n form.append(\"application\", JSON.stringify(applicationManifest));\n form.append(\n \"upgrade_requests_to_latest_code\",\n String(upgradeRunningRequests),\n );\n\n await this.http.requestResponse(\"POST\", this.namespacePath(\"applications\"), {\n body: form,\n });\n }\n\n async deleteApplication(applicationName: string): Promise<void> {\n await this.http.requestResponse(\n \"DELETE\",\n this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),\n );\n }\n\n async deleteSandboxImage(imageName: string): Promise<void> {\n await this.http.requestResponse(\n \"DELETE\",\n this.namespacePath(`sandbox-images/${encodeURIComponent(imageName)}`),\n );\n }\n\n /**\n * Look up a registered sandbox image (template) by its registered name.\n *\n * Returns the template, or `null` when no image with that name exists.\n * API-key clients may omit organization/project IDs and use the\n * token-scoped Platform API route directly. Explicit scope remains\n * available for PAT callers.\n */\n async findSandboxImageByName(\n imageName: string,\n options?: { organizationId?: string; projectId?: string },\n ): Promise<SandboxTemplate | null> {\n const base = this.platformProjectPath(\n \"sandbox-templates\",\n options?.organizationId,\n options?.projectId,\n );\n const response = await this.http.requestResponse(\n \"GET\",\n `${base}/by-name/${encodeURIComponent(imageName)}`,\n { allowedErrorStatusCodes: new Set([404]) },\n );\n if (response.status === 404) {\n return null;\n }\n const raw = await parseJsonResponse<Record<string, unknown>>(response);\n return fromSnakeKeys(raw) as SandboxTemplate;\n }\n\n /**\n * List all registered sandbox images (templates), following pagination to\n * the end. API-key clients may omit organization/project IDs and use the\n * token-scoped Platform API route directly.\n */\n async listSandboxImages(\n options?: { organizationId?: string; projectId?: string },\n ): Promise<SandboxTemplate[]> {\n const base = this.platformProjectPath(\n \"sandbox-templates\",\n options?.organizationId,\n options?.projectId,\n );\n let path: string | null = `${base}?pageSize=100`;\n const templates: SandboxTemplate[] = [];\n while (path !== null) {\n const page: SandboxTemplatesPage = await this.http.requestJson<SandboxTemplatesPage>(\n \"GET\",\n path,\n );\n for (const item of page.items ?? []) {\n templates.push(fromSnakeKeys(item) as SandboxTemplate);\n }\n const next = page.pagination?.next;\n path = next ? nextRequestPath(next) : null;\n }\n return templates;\n }\n\n async applications(): Promise<ApplicationSummary[]> {\n const raw = await this.http.requestJson<{ applications: Record<string, unknown>[] }>(\n \"GET\",\n this.namespacePath(\"applications\"),\n );\n return (raw.applications ?? []).map(\n (application) => fromSnakeKeys(application) as ApplicationSummary,\n );\n }\n\n async applicationManifest(applicationName: string): Promise<ApplicationManifest> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"GET\",\n this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),\n );\n return fromSnakeKeys(raw) as ApplicationManifest;\n }\n\n async runRequest(\n applicationName: string,\n inputs: RequestInput[] = [],\n ): Promise<string> {\n const path = this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}`,\n );\n\n const response =\n inputs.length === 0\n ? await this.http.requestResponse(\"POST\", path, {\n body: new Uint8Array(),\n headers: { Accept: \"application/json\" },\n })\n : inputs.length === 1 && inputs[0].name === \"0\"\n ? await this.http.requestResponse(\"POST\", path, {\n body: toRequestBody(inputs[0].data),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": inputs[0].contentType,\n },\n })\n : await this.runMultipartRequest(path, inputs);\n\n const body = await parseJsonResponse<{ request_id?: string }>(response);\n const requestId = body?.request_id;\n if (!requestId) {\n throw new Error(\"missing request_id in run request response body\");\n }\n return requestId;\n }\n\n async waitOnRequestCompletion(\n applicationName: string,\n requestId: string,\n ): Promise<void> {\n const stream = await this.http.requestStream(\n \"GET\",\n this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/progress`,\n ),\n );\n\n for await (const event of parseSSEStream<Record<string, unknown>>(stream)) {\n if (Object.prototype.hasOwnProperty.call(event, \"RequestFinished\")) {\n return;\n }\n }\n\n throw new Error(\"progress stream ended before request completion\");\n }\n\n async requestMetadata(\n applicationName: string,\n requestId: string,\n ): Promise<RequestMetadata> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"GET\",\n this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}`,\n ),\n );\n return fromSnakeKeys(raw) as RequestMetadata;\n }\n\n async requestOutput(\n applicationName: string,\n requestId: string,\n ): Promise<RequestOutput> {\n const response = await this.http.requestResponse(\n \"GET\",\n this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/output`,\n ),\n );\n\n const serializedValue = new Uint8Array(await response.arrayBuffer());\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n return {\n serializedValue,\n contentType,\n };\n }\n\n async listSecrets(options?: {\n organizationId?: string;\n projectId?: string;\n pageSize?: number;\n }): Promise<SecretsList> {\n const base = this.secretCollectionPath(\n options?.organizationId,\n options?.projectId,\n );\n const raw = await this.http.requestJson<SecretMetadata[]>(\"GET\", base);\n const pageSize = Math.max(0, options?.pageSize ?? 100);\n return Object.assign(\n {\n items: raw.slice(0, pageSize).map(secretFromMetadata),\n pagination: { total: raw.length },\n },\n { traceId: raw.traceId },\n );\n }\n\n async getSecret(\n secretId: string,\n options?: { organizationId?: string; projectId?: string },\n ): Promise<Secret> {\n const base = this.secretCollectionPath(\n options?.organizationId,\n options?.projectId,\n );\n const raw = await this.http.requestJson<SecretMetadata>(\n \"GET\",\n `${base}/${encodeURIComponent(secretId)}`,\n );\n return Object.assign(secretFromMetadata(raw), { traceId: raw.traceId });\n }\n\n async upsertSecrets(\n secrets: NewSecret | NewSecret[],\n options?: { organizationId?: string; projectId?: string },\n ): Promise<UpsertSecretResponse> {\n const base = this.secretCollectionPath(\n options?.organizationId,\n options?.projectId,\n );\n if (Array.isArray(secrets)) {\n const results: Secret[] = [];\n for (const secret of secrets) {\n results.push(await this.upsertSecret(base, secret));\n }\n return results;\n }\n return this.upsertSecret(base, secrets);\n }\n\n async deleteSecret(\n secretId: string,\n options?: { organizationId?: string; projectId?: string },\n ): Promise<void> {\n const base = this.secretCollectionPath(\n options?.organizationId,\n options?.projectId,\n );\n await this.http.requestResponse(\n \"DELETE\",\n `${base}/${encodeURIComponent(secretId)}`,\n );\n }\n\n private async upsertSecret(base: string, secret: NewSecret): Promise<Secret> {\n let response = await this.http.requestResponse(\"POST\", base, {\n json: secret,\n headers: { \"Idempotency-Key\": nanoid() },\n allowedErrorStatusCodes: new Set([409]),\n });\n if (response.status === 409) {\n const prefix = base.slice(0, -\"/secrets\".length);\n const existing = await this.http.requestJson<{ id: string }>(\n \"GET\",\n `${prefix}/secret-names/${encodeURIComponent(secret.name)}`,\n );\n response = await this.http.requestResponse(\n \"POST\",\n `${base}/${encodeURIComponent(existing.id)}/versions`,\n {\n json: { value: secret.value },\n headers: { \"Idempotency-Key\": nanoid() },\n },\n );\n }\n const metadata = await parseJsonResponse<SecretMetadata>(response);\n return Object.assign(secretFromMetadata(metadata), {\n traceId: response.traceId,\n });\n }\n\n async startImageBuild(\n buildServicePath: string,\n request: StartImageBuildRequest,\n ): Promise<BuildInfo> {\n const form = new FormData();\n form.append(\"graph_name\", request.applicationName);\n form.append(\"graph_version\", request.applicationVersion);\n form.append(\"graph_function_name\", request.functionName);\n form.append(\"image_name\", request.imageName);\n form.append(\"image_id\", request.imageId);\n form.append(\n \"context\",\n new Blob([toBlobPart(request.buildContext)]),\n \"context.tar.gz\",\n );\n\n const response = await this.http.requestResponse(\n \"PUT\",\n `${trimTrailingSlashes(buildServicePath)}/builds`,\n { body: form },\n );\n const raw = await parseJsonResponse<Record<string, unknown>>(response);\n return fromSnakeKeys(raw) as BuildInfo;\n }\n\n async createApplicationBuild(\n buildServicePath: string,\n request: CreateApplicationBuildRequest,\n imageContexts: ApplicationBuildContext[],\n ): Promise<ApplicationBuildResponse> {\n const form = createApplicationBuildForm(request, imageContexts);\n const response = await this.http.requestResponse(\n \"POST\",\n trimTrailingSlashes(buildServicePath),\n { body: form },\n );\n const raw = await parseJsonResponse<Record<string, unknown>>(response);\n return fromSnakeKeys(raw) as ApplicationBuildResponse;\n }\n\n async applicationBuildInfo(\n buildServicePath: string,\n applicationBuildId: string,\n ): Promise<ApplicationBuildResponse> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"GET\",\n `${trimTrailingSlashes(buildServicePath)}/${encodeURIComponent(applicationBuildId)}`,\n );\n return fromSnakeKeys(raw) as ApplicationBuildResponse;\n }\n\n async cancelApplicationBuild(\n buildServicePath: string,\n applicationBuildId: string,\n ): Promise<ApplicationBuildResponse> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"POST\",\n `${trimTrailingSlashes(buildServicePath)}/${encodeURIComponent(applicationBuildId)}/cancel`,\n );\n return fromSnakeKeys(raw) as ApplicationBuildResponse;\n }\n\n async buildInfo(\n buildServicePath: string,\n buildId: string,\n ): Promise<BuildInfo> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"GET\",\n `${trimTrailingSlashes(buildServicePath)}/builds/${encodeURIComponent(buildId)}`,\n );\n return fromSnakeKeys(raw) as BuildInfo;\n }\n\n async cancelBuild(buildServicePath: string, buildId: string): Promise<void> {\n await this.http.requestResponse(\n \"POST\",\n `${trimTrailingSlashes(buildServicePath)}/builds/${encodeURIComponent(buildId)}/cancel`,\n );\n }\n\n async *streamBuildLogs(\n buildServicePath: string,\n buildId: string,\n signal?: AbortSignal,\n ): AsyncIterable<BuildLogEntry> {\n const stream = await this.http.requestStream(\n \"GET\",\n `${trimTrailingSlashes(buildServicePath)}/builds/${encodeURIComponent(buildId)}/logs`,\n { signal },\n );\n for await (const event of parseSSEStream<Record<string, unknown>>(stream, signal)) {\n yield fromSnakeKeys(event) as BuildLogEntry;\n }\n }\n\n private async runMultipartRequest(\n path: string,\n inputs: RequestInput[],\n ): Promise<Response> {\n const form = new FormData();\n for (const input of inputs) {\n form.append(\n input.name,\n new Blob([toBlobPart(input.data)], { type: input.contentType }),\n input.name,\n );\n }\n return this.http.requestResponse(\"POST\", path, {\n body: form,\n headers: { Accept: \"application/json\" },\n });\n }\n\n private namespacePath(subpath: string): string {\n return `/v1/namespaces/${encodeURIComponent(this.namespace)}/${subpath.replace(/^\\/+/, \"\")}`;\n }\n\n private async existingApplicationPublicEndpointId(\n applicationName: string,\n ): Promise<string | undefined> {\n const response = await this.http.requestResponse(\n \"GET\",\n this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),\n { allowedErrorStatusCodes: new Set([404]) },\n );\n if (response.status === 404) {\n return undefined;\n }\n\n const application =\n await parseJsonResponse<Record<string, unknown>>(response);\n return publicEndpointIdFromManifest(application);\n }\n\n private platformProjectPath(\n resource: \"sandbox-templates\",\n organizationId?: string,\n projectId?: string,\n ): string {\n const resolvedOrganizationId = organizationId ?? this.organizationId;\n const resolvedProjectId = projectId ?? this.projectId;\n if (!resolvedOrganizationId && !resolvedProjectId) {\n return `/platform/v1/${resource}`;\n }\n if (!resolvedOrganizationId || !resolvedProjectId) {\n throw new Error(\n \"organizationId and projectId must be provided together\",\n );\n }\n return `/platform/v1/organizations/${encodeURIComponent(resolvedOrganizationId)}/projects/${encodeURIComponent(resolvedProjectId)}/${resource}`;\n }\n\n private secretCollectionPath(\n organizationId?: string,\n projectId?: string,\n ): string {\n const resolvedOrganizationId = organizationId ?? this.organizationId;\n const resolvedProjectId = projectId ?? this.projectId;\n if (!resolvedOrganizationId && !resolvedProjectId) {\n return this.namespacePath(\"secrets\");\n }\n if (!resolvedOrganizationId || !resolvedProjectId) {\n throw new Error(\"organizationId and projectId must be provided together\");\n }\n return this.namespacePath(\"secrets\");\n }\n}\n\ntype SecretMetadata = {\n id: string;\n name: string;\n created_at_ms: number;\n};\n\nfunction secretFromMetadata(metadata: SecretMetadata): Secret {\n return {\n id: metadata.id,\n name: metadata.name,\n createdAt: new Date(metadata.created_at_ms),\n };\n}\n\nconst UNAUTHENTICATED_REQUESTS = \"unauthenticated_requests\";\n\nfunction applicationAllowsUnauthenticatedRequests(\n manifest: ApplicationManifest,\n): boolean {\n return (\n Array.isArray(manifest.allow) &&\n manifest.allow.includes(UNAUTHENTICATED_REQUESTS)\n );\n}\n\nfunction publicEndpointIdFromManifest(\n manifest: ApplicationManifest,\n): string | undefined {\n for (const key of [\"public_endpoint_id\", \"publicEndpointId\"]) {\n const value = manifest[key];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction generatePublicEndpointId(): string {\n return `endpoint_${nanoid()}`;\n}\n\nfunction createApplicationBuildForm(\n request: CreateApplicationBuildRequest,\n imageContexts: ApplicationBuildContext[],\n): FormData {\n const contextsByPartName = new Map<string, ApplicationBuildContext>();\n for (const context of imageContexts) {\n if (contextsByPartName.has(context.contextTarPartName)) {\n throw new Error(\n `duplicate image context part name '${context.contextTarPartName}'`,\n );\n }\n contextsByPartName.set(context.contextTarPartName, context);\n }\n\n const form = new FormData();\n form.append(\n \"app_version\",\n new Blob([JSON.stringify(request)], { type: \"application/json\" }),\n \"app_version\",\n );\n\n for (const image of request.images) {\n const context = contextsByPartName.get(image.contextTarPartName);\n if (!context) {\n throw new Error(\n `missing image context for part '${image.contextTarPartName}'`,\n );\n }\n form.append(\n image.contextTarPartName,\n new Blob([toBlobPart(context.contextTarGz)]),\n `${image.contextTarPartName}.tar.gz`,\n );\n }\n\n for (const context of imageContexts) {\n if (!request.images.some((image) => image.contextTarPartName === context.contextTarPartName)) {\n throw new Error(\n `unexpected image context for part '${context.contextTarPartName}'`,\n );\n }\n }\n\n return form;\n}\n\nfunction trimTrailingSlashes(value: string): string {\n return value.endsWith(\"/\") ? value.slice(0, -1) : value;\n}\n\n/** One page of the paginated sandbox-templates list response. */\ninterface SandboxTemplatesPage {\n items?: Record<string, unknown>[];\n pagination?: { next?: string };\n}\n\n/**\n * Reduce a `pagination.next` link to a base-URL-relative request path. The\n * server may return either an absolute URL or an absolute path; the HTTP\n * client always prepends its base URL, so absolute URLs must be reduced to\n * their path+query first.\n */\nfunction nextRequestPath(next: string): string {\n const schemeIndex = next.indexOf(\"://\");\n if (schemeIndex !== -1) {\n const afterScheme = next.slice(schemeIndex + 3);\n const slashIndex = afterScheme.indexOf(\"/\");\n return slashIndex === -1 ? \"/\" : afterScheme.slice(slashIndex);\n }\n return next.startsWith(\"/\") ? next : `/${next}`;\n}\n\nfunction toBlobPart(data: BinaryPayload): string | Blob | ArrayBuffer {\n if (typeof data === \"string\" || data instanceof Blob) {\n return data;\n }\n if (data instanceof Uint8Array) {\n return Uint8Array.from(data).buffer;\n }\n return data;\n}\n\nfunction toRequestBody(data: BinaryPayload): string | Blob | ArrayBuffer {\n return toBlobPart(data);\n}\n\nasync function parseJsonResponse<T>(response: Response): Promise<T> {\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n}\n","import { randomUUID } from \"node:crypto\";\n\n// Erased at runtime — safe despite the module cycle with sandbox-image.ts,\n// which imports Image from here.\nimport type { CreateSandboxImageOptions } from \"./sandbox-image.js\";\n\nconst DEFAULT_IMAGE_NAME = \"default\";\n\nexport const ImageBuildOperationType = {\n ADD: \"ADD\",\n COPY: \"COPY\",\n ENV: \"ENV\",\n RUN: \"RUN\",\n WORKDIR: \"WORKDIR\",\n} as const;\n\nexport type ImageBuildOperationType =\n (typeof ImageBuildOperationType)[keyof typeof ImageBuildOperationType];\n\nexport interface ImageBuildOperation {\n type: ImageBuildOperationType;\n args: string[];\n options: Record<string, string>;\n}\n\nexport interface ImageOptions {\n name?: string;\n tag?: string;\n baseImage?: string | null;\n}\n\nfunction cloneOperation(op: ImageBuildOperation): ImageBuildOperation {\n return {\n type: op.type,\n args: [...op.args],\n options: { ...op.options },\n };\n}\n\nexport class Image {\n readonly _id: string;\n readonly _name: string;\n readonly _tag: string;\n readonly _baseImage: string | null;\n readonly _buildOperations: ImageBuildOperation[];\n\n constructor();\n constructor(name: string, tag?: string, baseImage?: string | null);\n constructor(options: ImageOptions);\n constructor(\n nameOrOptions: string | ImageOptions = {},\n tag = \"latest\",\n baseImage: string | null = null,\n ) {\n this._id = randomUUID();\n this._buildOperations = [];\n\n if (typeof nameOrOptions === \"string\") {\n this._name = nameOrOptions;\n this._tag = tag;\n this._baseImage = baseImage;\n return;\n }\n\n this._name = nameOrOptions.name ?? DEFAULT_IMAGE_NAME;\n this._tag = nameOrOptions.tag ?? \"latest\";\n this._baseImage = nameOrOptions.baseImage ?? null;\n }\n\n get name(): string {\n return this._name;\n }\n\n get tag(): string {\n return this._tag;\n }\n\n get baseImage(): string | null {\n return this._baseImage;\n }\n\n get buildOperations(): ImageBuildOperation[] {\n return this._buildOperations.map(cloneOperation);\n }\n\n add(\n src: string,\n dest: string,\n options: Record<string, string> | undefined = undefined,\n ): this {\n return this._addOperation({\n type: ImageBuildOperationType.ADD,\n args: [src, dest],\n options: options == null ? {} : { ...options },\n });\n }\n\n copy(\n src: string,\n dest: string,\n options: Record<string, string> | undefined = undefined,\n ): this {\n return this._addOperation({\n type: ImageBuildOperationType.COPY,\n args: [src, dest],\n options: options == null ? {} : { ...options },\n });\n }\n\n env(key: string, value: string): this {\n return this._addOperation({\n type: ImageBuildOperationType.ENV,\n args: [key, value],\n options: {},\n });\n }\n\n run(\n commands: string | string[],\n options: Record<string, string> | undefined = undefined,\n ): this {\n return this._addOperation({\n type: ImageBuildOperationType.RUN,\n args: Array.isArray(commands) ? [...commands] : [commands],\n options: options == null ? {} : { ...options },\n });\n }\n\n workdir(directory: string): this {\n return this._addOperation({\n type: ImageBuildOperationType.WORKDIR,\n args: [directory],\n options: {},\n });\n }\n\n /**\n * Build this image as a sandbox template and register it.\n *\n * Materializes the image in a build sandbox, snapshots the filesystem,\n * and registers the snapshot as a named sandbox template.\n */\n async build(\n options: CreateSandboxImageOptions = {},\n ): Promise<Record<string, unknown>> {\n const { createSandboxImage } = await import(\"./sandbox-image.js\");\n return createSandboxImage(this, options);\n }\n\n private _addOperation(op: ImageBuildOperation): this {\n this._buildOperations.push(op);\n return this;\n }\n}\n\nfunction renderOptions(options: Record<string, string>): string {\n const entries = Object.entries(options);\n if (entries.length === 0) {\n return \"\";\n }\n return ` ${entries.map(([key, value]) => `--${key}=${value}`).join(\" \")}`;\n}\n\nfunction renderBuildOp(op: ImageBuildOperation): string {\n const options = renderOptions(op.options);\n if (op.type === ImageBuildOperationType.ENV) {\n return `ENV${options} ${op.args[0]}=${JSON.stringify(op.args[1])}`;\n }\n return `${op.type}${options} ${op.args.join(\" \")}`;\n}\n\nexport function dockerfileContent(image: Image): string {\n const lines = image.baseImage == null ? [] : [`FROM ${image.baseImage}`];\n lines.push(...image.buildOperations.map((op) => renderBuildOp(op)));\n return lines.join(\"\\n\");\n}\n","// Read the ELF interpreter, rather than generating a process-wide diagnostic\n// report. Both supported Linux architectures use little-endian ELF64. Reads\n// are bounded to the header, program headers, and interpreter pathname.\nfunction detectLinuxLibc(fs, executable = process.execPath) {\n const override = process.env.TENSORLAKE_NODE_LIBC;\n if (override != null) {\n if (override === \"gnu\" || override === \"musl\") return override;\n throw new Error(\"TENSORLAKE_NODE_LIBC must be 'gnu' or 'musl'.\");\n }\n\n let fd;\n try {\n fd = fs.openSync(executable, \"r\");\n function read(size, offset) {\n if (!Number.isSafeInteger(offset) || offset < 0) {\n throw new Error(\"Invalid ELF offset\");\n }\n const buffer = Buffer.alloc(size);\n let count = 0;\n while (count < size) {\n const bytes = fs.readSync(fd, buffer, count, size - count, offset + count);\n if (bytes === 0) throw new Error(\"Truncated ELF executable\");\n count += bytes;\n }\n return buffer;\n }\n\n const header = read(64, 0);\n if (header.readUInt32BE(0) !== 0x7f454c46 || header[4] !== 2 || header[5] !== 1) {\n throw new Error(\"Expected a little-endian ELF64 executable\");\n }\n const entrySize = header.readUInt16LE(54);\n const count = header.readUInt16LE(56);\n if (entrySize !== 56 || count === 0 || count > 128) {\n throw new Error(\"Unsupported ELF program headers\");\n }\n const entries = read(entrySize * count, Number(header.readBigUInt64LE(32)));\n for (let i = 0; i < count; i++) {\n const offset = i * entrySize;\n if (entries.readUInt32LE(offset) !== 3) continue; // PT_INTERP\n const size = Number(entries.readBigUInt64LE(offset + 32));\n if (size < 2 || size > 4096) throw new Error(\"Invalid ELF interpreter size\");\n const interpreter = read(size, Number(entries.readBigUInt64LE(offset + 8)));\n if (interpreter[size - 1] !== 0) throw new Error(\"Unterminated ELF interpreter\");\n const name = interpreter.subarray(0, -1).toString(\"utf8\").split(\"/\").at(-1);\n if (name.startsWith(\"ld-musl-\")) return \"musl\";\n if (name.startsWith(\"ld-linux-\")) return \"gnu\";\n throw new Error(\"Unrecognized ELF interpreter\");\n }\n throw new Error(\"No ELF interpreter (statically linked executable)\");\n } catch (cause) {\n throw new Error(\n \"Unable to detect Linux libc from the Node executable. Set TENSORLAKE_NODE_LIBC to 'gnu' or 'musl' for a nonstandard runtime.\",\n { cause },\n );\n } finally {\n if (fd != null) fs.closeSync(fd);\n }\n}\n\nmodule.exports = { detectLinuxLibc };\n","import { detectLinuxLibc } from \"../lib/libc.cjs\";\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\ninterface RuntimeReport {\n header?: {\n glibcVersionRuntime?: string;\n };\n}\n\ninterface TargetOptions {\n libc?: \"gnu\" | \"musl\";\n report?: RuntimeReport;\n}\n\ninterface NativeBindingPathOptions extends TargetOptions {\n packageRoot?: string;\n platform?: NodeJS.Platform;\n arch?: string;\n}\n\nconst NATIVE_PACKAGES: Readonly<Record<string, string>> = {\n \"darwin-arm64\": \"tensorlake-native-darwin-arm64\",\n \"linux-arm64\": \"tensorlake-native-linux-arm64-gnu\",\n \"linux-arm64-musl\": \"tensorlake-native-linux-arm64-musl\",\n \"linux-x64\": \"tensorlake-native-linux-x64-gnu\",\n \"linux-x64-musl\": \"tensorlake-native-linux-x64-musl\",\n \"win32-x64\": \"tensorlake-native-win32-x64\",\n};\n\nfunction packageRoot(): string {\n const parent = fileURLToPath(new URL(\"../\", import.meta.url));\n if (fs.existsSync(path.join(parent, \"package.json\"))) return parent;\n const grandparent = fileURLToPath(new URL(\"../../\", import.meta.url));\n if (fs.existsSync(path.join(grandparent, \"package.json\"))) return grandparent;\n return parent;\n}\n\nlet cachedLinuxLibc: \"gnu\" | \"musl\" | undefined;\n\nfunction linuxLibcFamily(options: TargetOptions): \"gnu\" | \"musl\" {\n if (options.libc != null) return options.libc;\n if (options.report != null) {\n return options.report.header?.glibcVersionRuntime ? \"gnu\" : \"musl\";\n }\n if (cachedLinuxLibc != null) return cachedLinuxLibc;\n\n cachedLinuxLibc = detectLinuxLibc(fs);\n return cachedLinuxLibc;\n}\n\nexport function nativeTargetId(\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n options: TargetOptions = {},\n): string {\n const target = `${platform}-${arch}`;\n if (platform !== \"linux\") return target;\n if (options.libc == null && options.report == null && platform !== process.platform) {\n return target;\n }\n return linuxLibcFamily(options) === \"musl\" ? `${target}-musl` : target;\n}\n\nexport function nativeBindingPath(options: NativeBindingPathOptions = {}): string {\n const platform = options.platform ?? process.platform;\n const arch = options.arch ?? process.arch;\n return path.join(\n options.packageRoot ?? packageRoot(),\n \"dist\",\n \"native\",\n nativeTargetId(platform, arch, options),\n \"tensorlake-node.node\",\n );\n}\n\nexport function nativePackageName(\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n options: TargetOptions = {},\n): string | undefined {\n return NATIVE_PACKAGES[nativeTargetId(platform, arch, options)];\n}\n\nexport function loadNative<T>(): T {\n const target = nativeTargetId();\n const bindingPath = nativeBindingPath();\n const require = createRequire(import.meta.url);\n\n // Local source builds stage the addon here. Published packages intentionally\n // omit this directory and resolve the platform-specific optional dependency.\n if (fs.existsSync(bindingPath)) return require(bindingPath) as T;\n\n const packageName = nativePackageName();\n if (!packageName) {\n throw new Error(\n `Tensorlake does not provide a native binding for ${target}.`,\n );\n }\n\n let packageEntry: string;\n try {\n packageEntry = require.resolve(packageName);\n } catch (cause) {\n throw new Error(\n `Missing native binding package ${packageName} for ${target}. Reinstall tensorlake without omitting optional dependencies, and install dependencies on the machine where they will run.`,\n { cause },\n );\n }\n return require(packageEntry) as T;\n}\n","import path from \"node:path\";\nimport os from \"node:os\";\nimport { existsSync, mkdtempSync, rmSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\nimport { CloudClient } from \"./cloud-client.js\";\nimport type { SandboxTemplate } from \"./cloud-models.js\";\nimport { Image, ImageBuildOperationType, dockerfileContent } from \"./image.js\";\nimport type { ImageBuildOperation } from \"./image.js\";\nimport { loadNative } from \"./native-binding.js\";\n\n/**\n * Sandbox-image build engine.\n *\n * Renders the source to a Dockerfile (for `Image` inputs) and hands the\n * Dockerfile path/text + context to the Rust core via the platform-specific native binding,\n * which parses, validates, materializes, and registers the image. The Rust\n * core owns parsing and the warnings for instructions that run during the\n * build but have no effect when a sandbox runs from the image\n * (`ONBUILD`/`SHELL`/`EXPOSE`/`HEALTHCHECK`/`LABEL`/`STOPSIGNAL`/`VOLUME`).\n */\n\nexport interface CreateSandboxImageOptions {\n registeredName?: string;\n cpus?: number;\n memoryMb?: number;\n diskMb?: number;\n builderDiskMb?: number;\n isPublic?: boolean;\n /**\n * Build context directory for an `Image` source, used exactly like\n * `docker build <contextDir>`: it is uploaded as-is and COPY/ADD sources\n * resolve relative to it. Required when the image has COPY/ADD ops that read\n * host files — building without it then throws. When the image has no such\n * ops it may be omitted, and an empty context (just the generated Dockerfile)\n * is uploaded so cwd is not archived. Ignored when the source is a Dockerfile\n * path (the Dockerfile's parent directory is used instead).\n */\n contextDir?: string;\n /**\n * Use Docker/BuildKit max compatibility mode (build is slower and uses more\n * memory and disk space on builder sandbox).\n */\n dockerCompat?: boolean;\n /**\n * Print build progress to stderr. Ignored when an explicit `emit` is\n * passed via `deps`. Defaults to false — `createSandboxImage` is silent\n * by default when invoked programmatically (e.g. `Image.build()`).\n */\n verbose?: boolean;\n}\n\nexport interface ImportSandboxImageOptions {\n /**\n * Name to register the image under. Defaults to the image reference's last\n * path segment with any tag/digest stripped (e.g. `pytorch/pytorch:2.4.1`\n * -> `pytorch`).\n */\n registeredName?: string;\n cpus?: number;\n memoryMb?: number;\n diskMb?: number;\n builderDiskMb?: number;\n isPublic?: boolean;\n /**\n * Use Docker/BuildKit max compatibility mode (import is slower and uses more\n * memory and disk space on builder sandbox).\n */\n dockerCompat?: boolean;\n /**\n * Print build progress to stderr. Ignored when an explicit `emit` is\n * passed via `deps`. Defaults to false.\n */\n verbose?: boolean;\n}\n\nexport type SandboxImageSource = string | Image;\n\nexport interface CreateSandboxImageDeps {\n emit?: (event: Record<string, unknown>) => void;\n /** @internal Standalone CLI entry points allow PAT auth; SDK callers do not. */\n _allowPat?: boolean;\n}\n\n// --- Native binding loader -------------------------------------------------\n\n/** Auth/context + resource fields shared by the build and import bindings. */\ninterface NativeBindingCommonOptions {\n apiUrl: string;\n bearerToken: string;\n registeredName?: string | undefined | null;\n diskMb?: number | undefined | null;\n builderDiskMb?: number | undefined | null;\n cpus?: number | undefined | null;\n memoryMb?: number | undefined | null;\n isPublic?: boolean | undefined | null;\n organizationId?: string | undefined | null;\n projectId?: string | undefined | null;\n namespace?: string | undefined | null;\n useScopeHeaders?: boolean | undefined | null;\n userAgent?: string | undefined | null;\n dockerCompat?: boolean | undefined | null;\n}\n\ninterface NativeBindingOptions extends NativeBindingCommonOptions {\n dockerfilePath: string;\n dockerfileText?: string | undefined | null;\n contextDir?: string | undefined | null;\n}\n\ninterface NativeBindingImportOptions extends NativeBindingCommonOptions {\n imageReference: string;\n}\n\ninterface NativeBindingEvent {\n eventType: string;\n stream?: string | undefined | null;\n message: string;\n}\n\ninterface NativeBinding {\n buildSandboxImage(\n options: NativeBindingOptions,\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n ): Promise<string>;\n importSandboxImage(\n options: NativeBindingImportOptions,\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n ): Promise<string>;\n}\n\nlet cachedNativeBinding: NativeBinding | undefined;\nlet cachedNativeBindingError: Error | undefined;\n\nfunction loadNativeBinding(): NativeBinding {\n if (cachedNativeBinding) return cachedNativeBinding;\n if (cachedNativeBindingError) throw cachedNativeBindingError;\n try {\n cachedNativeBinding = loadNative<NativeBinding>();\n return cachedNativeBinding;\n } catch (error) {\n cachedNativeBindingError =\n error instanceof Error ? error : new Error(String(error));\n throw cachedNativeBindingError;\n }\n}\n\n/** Test seam: replace the native binding with a stub. */\nexport function __setNativeBindingForTest(binding: NativeBinding | undefined): void {\n cachedNativeBinding = binding;\n cachedNativeBindingError = undefined;\n}\n\n// --- Build context ---------------------------------------------------------\n\nexport interface BuildContext {\n apiUrl: string;\n apiKey?: string;\n personalAccessToken?: string;\n namespace: string;\n organizationId?: string;\n projectId?: string;\n debug: boolean;\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n return value && value.length > 0 ? value : undefined;\n}\n\nexport function buildContextFromEnv(): BuildContext {\n const debugRaw = (process.env.TENSORLAKE_DEBUG ?? \"\").toLowerCase();\n const debug = [\"1\", \"true\", \"yes\", \"on\"].includes(debugRaw);\n return {\n apiUrl: nonEmpty(process.env.TENSORLAKE_API_URL) ?? \"https://api.tensorlake.ai\",\n apiKey: nonEmpty(process.env.TENSORLAKE_API_KEY),\n personalAccessToken: nonEmpty(process.env.TENSORLAKE_PAT),\n namespace: nonEmpty(process.env.INDEXIFY_NAMESPACE) ?? \"default\",\n organizationId: nonEmpty(process.env.TENSORLAKE_ORGANIZATION_ID),\n projectId: nonEmpty(process.env.TENSORLAKE_PROJECT_ID),\n debug,\n };\n}\n\n// --- Default-name helper ---------------------------------------------------\n\nconst DEFAULT_IMAGE_NAME = \"default\";\n\nfunction defaultRegisteredName(dockerfilePath: string): string {\n const parsed = path.parse(dockerfilePath);\n if (parsed.name.toLowerCase() === \"dockerfile\") {\n const parentName = path.basename(path.dirname(dockerfilePath)).trim();\n return parentName || \"sandbox-image\";\n }\n return parsed.name || \"sandbox-image\";\n}\n\n/**\n * Mirror the Rust core's default name derivation for image imports: the last\n * path segment of the reference with any tag/digest stripped\n * (e.g. `pytorch/pytorch:2.4.1` -> `pytorch`, `ghcr.io/org/app@sha256:...`\n * -> `app`).\n */\nfunction defaultRegisteredNameFromImage(imageReference: string): string {\n const withoutDigest = imageReference.split(\"@\", 1)[0] ?? imageReference;\n const lastSegment = withoutDigest.split(\"/\").pop() ?? withoutDigest;\n const colonIndex = lastSegment.lastIndexOf(\":\");\n const name =\n colonIndex > 0 && colonIndex < lastSegment.length - 1\n ? lastSegment.slice(0, colonIndex)\n : lastSegment;\n return name || \"imported-image\";\n}\n\n// --- Emit helpers ----------------------------------------------------------\n\nfunction noopEmit(_event: Record<string, unknown>): void {}\n\nfunction stderrEmit(event: Record<string, unknown>): void {\n const message = typeof event.message === \"string\" ? event.message : \"\";\n const type = typeof event.type === \"string\" ? event.type : \"\";\n if (type === \"build_log\") {\n const stream = typeof event.stream === \"string\" ? event.stream : \"stdout\";\n process.stderr.write(`[${stream}] ${message}\\n`);\n } else if (message) {\n process.stderr.write(`[${type}] ${message}\\n`);\n }\n}\n\nfunction ndjsonStdoutEmit(event: Record<string, unknown>): void {\n process.stdout.write(`${JSON.stringify(event)}\\n`);\n}\n\nfunction eventToEmitDict(event: NativeBindingEvent): Record<string, unknown> {\n const out: Record<string, unknown> = {\n type: event.eventType,\n message: event.message,\n };\n if (event.stream != null) out.stream = event.stream;\n return out;\n}\n\n/**\n * True when a `RUN` op bind-mounts the build context (reads host files).\n * A BuildKit `RUN --mount=type=bind` reads from the build context unless it\n * mounts `from=<stage/image>`. `bind` is the default mount type, so a mount\n * with no explicit `type` counts too. Other mount types\n * (`cache`/`tmpfs`/`secret`/`ssh`) don't read the build context.\n */\nfunction runOpMountsContext(op: ImageBuildOperation): boolean {\n if (op.type !== ImageBuildOperationType.RUN) {\n return false;\n }\n const mount = op.options.mount;\n if (mount == null || mount === \"\") {\n return false;\n }\n const fields: Record<string, string> = {};\n for (const token of mount.split(\",\")) {\n const eq = token.indexOf(\"=\");\n const key = (eq === -1 ? token : token.slice(0, eq)).trim();\n const value = eq === -1 ? \"\" : token.slice(eq + 1).trim();\n fields[key] = value;\n }\n if ((fields.type ?? \"bind\") !== \"bind\") {\n return false;\n }\n return !(\"from\" in fields);\n}\n\n/**\n * True when a build op reads files from the host build context.\n * `COPY`/`ADD` with host sources need a context; a `RUN` with a\n * `--mount=type=bind` (the default type) reads it too. `COPY --from=<stage>`,\n * remote `ADD <url>`, `from=` bind mounts, and non-bind mounts don't.\n */\nfunction opReferencesHostFiles(op: ImageBuildOperation): boolean {\n if (op.type === ImageBuildOperationType.RUN) {\n return runOpMountsContext(op);\n }\n if (\n op.type !== ImageBuildOperationType.COPY &&\n op.type !== ImageBuildOperationType.ADD\n ) {\n return false;\n }\n if (op.options.from != null) {\n return false;\n }\n if (\n op.type === ImageBuildOperationType.ADD &&\n (op.args[0].startsWith(\"http://\") || op.args[0].startsWith(\"https://\"))\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * True if the image has ops that read files from the host (COPY/ADD host\n * sources, or a RUN bind mount). Such builds need a build context to resolve\n * those sources, so the caller must pass `contextDir` (mirroring\n * `docker build <context>`).\n */\nfunction imageRequiresContext(image: Image): boolean {\n return image.buildOperations.some(opReferencesHostFiles);\n}\n\n// --- Public API ------------------------------------------------------------\n\nexport async function createSandboxImage(\n source: SandboxImageSource,\n options: CreateSandboxImageOptions = {},\n deps: CreateSandboxImageDeps = {},\n): Promise<Record<string, unknown>> {\n const emit = deps.emit ?? (options.verbose ? stderrEmit : noopEmit);\n const context = buildContextFromEnv();\n\n let dockerfilePath: string;\n let dockerfileText: string | undefined;\n let nativeContextDir: string | undefined;\n let effectiveName: string;\n // Throwaway empty build context created when an Image build has no explicit\n // contextDir. Removed in the finally below.\n let tempContextDir: string | undefined;\n\n if (source instanceof Image) {\n if (!source.baseImage) {\n throw new Error(\"Image must have a baseImage to build\");\n }\n // With an explicit contextDir we upload that directory as-is, like\n // `docker build <dir>`. Without one, an image that reads host files via\n // COPY/ADD can't be built (there is no context to resolve them against);\n // images without such ops get an empty context (just the Dockerfile) so\n // the whole cwd is not archived.\n let resolvedContext: string;\n if (options.contextDir != null) {\n resolvedContext = path.resolve(options.contextDir);\n } else if (imageRequiresContext(source)) {\n throw new Error(\n \"This image reads files from the host (via COPY/ADD or a RUN bind \" +\n \"mount), so it needs a build context. Pass `contextDir` pointing at \" +\n \"the directory that contains those sources; they resolve relative \" +\n \"to it, like `docker build <contextDir>`.\",\n );\n } else {\n tempContextDir = mkdtempSync(path.join(os.tmpdir(), \"tl-build-context-\"));\n resolvedContext = tempContextDir;\n }\n dockerfilePath = path.join(resolvedContext, \"Dockerfile\");\n let text = dockerfileContent(source);\n if (!text.endsWith(\"\\n\")) text += \"\\n\";\n dockerfileText = text;\n nativeContextDir = resolvedContext;\n effectiveName = options.registeredName ?? source.name;\n } else if (typeof source === \"string\") {\n const resolvedPath = path.resolve(source);\n if (!existsSync(resolvedPath)) {\n throw new Error(`Dockerfile not found: ${source}`);\n }\n dockerfilePath = resolvedPath;\n dockerfileText = undefined;\n nativeContextDir = undefined;\n effectiveName =\n options.registeredName ?? defaultRegisteredName(resolvedPath);\n } else {\n throw new TypeError(\n `source must be an Image or a Dockerfile path, got ${typeof source}`,\n );\n }\n\n try {\n if (effectiveName === DEFAULT_IMAGE_NAME) {\n console.warn(\n `Building sandbox image with the default name \"${DEFAULT_IMAGE_NAME}\". ` +\n \"Pass `registeredName` or `Image({ name })` to avoid collisions \" +\n \"with other default-named images in this project.\",\n );\n }\n\n const usePat = deps._allowPat === true && context.apiKey == null;\n const bearerToken = context.apiKey ?? (usePat ? context.personalAccessToken : undefined);\n if (!bearerToken) {\n if (context.personalAccessToken && !deps._allowPat) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\n deps._allowPat\n ? \"Missing TENSORLAKE_API_KEY or TENSORLAKE_PAT credentials.\"\n : \"Missing TENSORLAKE_API_KEY credentials.\",\n );\n }\n\n emit({ type: \"status\", message: `Building image '${effectiveName}'...` });\n\n const binding = loadNativeBinding();\n let emitError: unknown;\n const resultJson = await binding.buildSandboxImage(\n {\n apiUrl: context.apiUrl,\n bearerToken,\n dockerfilePath,\n registeredName: effectiveName,\n diskMb: options.diskMb,\n builderDiskMb: options.builderDiskMb,\n cpus: options.cpus,\n memoryMb: options.memoryMb,\n isPublic: options.isPublic ?? false,\n organizationId: usePat ? context.organizationId : undefined,\n projectId: usePat ? context.projectId : undefined,\n namespace: context.namespace,\n useScopeHeaders: usePat,\n userAgent: undefined,\n dockerCompat: options.dockerCompat ?? false,\n dockerfileText,\n contextDir: nativeContextDir,\n },\n (event) => {\n try {\n emit(eventToEmitDict(event));\n } catch (error) {\n emitError ??= error;\n }\n },\n );\n\n if (emitError != null) {\n throw emitError;\n }\n\n let result: Record<string, unknown> = {};\n if (resultJson.trim().length > 0) {\n result = JSON.parse(resultJson) as Record<string, unknown>;\n }\n emit({\n type: \"image_registered\",\n name: effectiveName,\n image_id:\n (typeof result.id === \"string\" && result.id) ||\n (typeof result.templateId === \"string\" && result.templateId) ||\n \"\",\n });\n emit({ type: \"done\" });\n return result;\n } finally {\n if (tempContextDir != null) {\n rmSync(tempContextDir, { recursive: true, force: true });\n }\n }\n}\n\n/**\n * Import a registry image directly into a sandbox image — no Docker.\n *\n * Unlike {@link createSandboxImage}, there is no Dockerfile and no build\n * context: the builder pulls the referenced image's layers and applies them\n * straight into the rootfs (via `oci-image-to-ext4`), bypassing the Docker\n * daemon entirely. This is the programmatic backend for the\n * `tl sbx image import` CLI command. The import is always a fresh base from\n * the registry — the reference is never resolved against the template\n * registry.\n */\nexport async function importSandboxImage(\n imageReference: string,\n options: ImportSandboxImageOptions = {},\n deps: CreateSandboxImageDeps = {},\n): Promise<Record<string, unknown>> {\n const emit = deps.emit ?? (options.verbose ? stderrEmit : noopEmit);\n\n if (typeof imageReference !== \"string\" || imageReference.trim().length === 0) {\n throw new Error(\"image reference to import must not be empty\");\n }\n const reference = imageReference.trim();\n\n const context = buildContextFromEnv();\n const effectiveName =\n options.registeredName ?? defaultRegisteredNameFromImage(reference);\n\n if (effectiveName === DEFAULT_IMAGE_NAME) {\n console.warn(\n `Importing sandbox image with the default name \"${DEFAULT_IMAGE_NAME}\". ` +\n \"Pass `registeredName` to avoid collisions with other default-named \" +\n \"images in this project.\",\n );\n }\n\n const usePat = deps._allowPat === true && context.apiKey == null;\n const bearerToken = context.apiKey ?? (usePat ? context.personalAccessToken : undefined);\n if (!bearerToken) {\n if (context.personalAccessToken && !deps._allowPat) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\n deps._allowPat\n ? \"Missing TENSORLAKE_API_KEY or TENSORLAKE_PAT credentials.\"\n : \"Missing TENSORLAKE_API_KEY credentials.\",\n );\n }\n\n emit({\n type: \"status\",\n message: `Importing image '${reference}' as '${effectiveName}'...`,\n });\n\n const binding = loadNativeBinding();\n let emitError: unknown;\n const resultJson = await binding.importSandboxImage(\n {\n apiUrl: context.apiUrl,\n bearerToken,\n imageReference: reference,\n registeredName: effectiveName,\n diskMb: options.diskMb,\n builderDiskMb: options.builderDiskMb,\n cpus: options.cpus,\n memoryMb: options.memoryMb,\n isPublic: options.isPublic ?? false,\n organizationId: usePat ? context.organizationId : undefined,\n projectId: usePat ? context.projectId : undefined,\n namespace: context.namespace,\n useScopeHeaders: usePat,\n userAgent: undefined,\n dockerCompat: options.dockerCompat ?? false,\n },\n (event) => {\n try {\n emit(eventToEmitDict(event));\n } catch (error) {\n emitError ??= error;\n }\n },\n );\n\n if (emitError != null) {\n throw emitError;\n }\n\n let result: Record<string, unknown> = {};\n if (resultJson.trim().length > 0) {\n result = JSON.parse(resultJson) as Record<string, unknown>;\n }\n emit({\n type: \"image_registered\",\n name: effectiveName,\n image_id:\n (typeof result.id === \"string\" && result.id) ||\n (typeof result.templateId === \"string\" && result.templateId) ||\n \"\",\n });\n emit({ type: \"done\" });\n return result;\n}\n\nexport async function deleteSandboxImage(imageName: string): Promise<void> {\n if (typeof imageName !== \"string\" || imageName.length === 0) {\n throw new TypeError(\"imageName must be a non-empty string\");\n }\n\n const context = buildContextFromEnv();\n const bearerToken = context.apiKey;\n if (!bearerToken) {\n if (context.personalAccessToken) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\"Missing TENSORLAKE_API_KEY credentials.\");\n }\n\n const client = new CloudClient({\n apiUrl: context.apiUrl,\n apiKey: bearerToken,\n namespace: context.namespace,\n });\n try {\n await client.deleteSandboxImage(imageName);\n } finally {\n client.close();\n }\n}\n\n/**\n * Look up a registered sandbox image by its registered name.\n *\n * Returns the registered sandbox template, or `null` if no image with that\n * name exists. Uses the same environment-based Tensorlake auth as\n * `createSandboxImage`. Ingress derives project scope from the API key.\n */\nexport async function findSandboxImageByName(\n imageName: string,\n): Promise<SandboxTemplate | null> {\n if (typeof imageName !== \"string\" || imageName.length === 0) {\n throw new TypeError(\"imageName must be a non-empty string\");\n }\n\n const context = buildContextFromEnv();\n const bearerToken = context.apiKey;\n if (!bearerToken) {\n if (context.personalAccessToken) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\"Missing TENSORLAKE_API_KEY credentials.\");\n }\n\n const client = new CloudClient({\n apiUrl: context.apiUrl,\n apiKey: bearerToken,\n namespace: context.namespace,\n });\n try {\n return await client.findSandboxImageByName(imageName);\n } finally {\n client.close();\n }\n}\n\n/**\n * List all registered sandbox images for the current project.\n *\n * Returns the registered sandbox templates (each with `id`, `name`,\n * `snapshotId`, `public`, etc.). Uses the same environment-based Tensorlake\n * auth as `createSandboxImage`. Ingress derives project scope from the API key.\n */\nexport async function listSandboxImages(): Promise<SandboxTemplate[]> {\n const context = buildContextFromEnv();\n const bearerToken = context.apiKey;\n if (!bearerToken) {\n if (context.personalAccessToken) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\"Missing TENSORLAKE_API_KEY credentials.\");\n }\n\n const client = new CloudClient({\n apiUrl: context.apiUrl,\n apiKey: bearerToken,\n namespace: context.namespace,\n });\n try {\n return await client.listSandboxImages();\n } finally {\n client.close();\n }\n}\n\nexport async function runCreateSandboxImageCli(argv = process.argv.slice(2)) {\n const parsed = parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n name: { type: \"string\", short: \"n\" },\n cpus: { type: \"string\" },\n memory: { type: \"string\" },\n disk_mb: { type: \"string\" },\n builder_disk_mb: { type: \"string\" },\n docker_compat: { type: \"boolean\", default: false },\n public: { type: \"boolean\", default: false },\n },\n });\n\n const dockerfilePath = parsed.positionals[0];\n if (!dockerfilePath) {\n throw new Error(\n \"Usage: tensorlake-create-sandbox-image <dockerfile_path> [--name NAME] [--cpus N] [--memory MB] [--disk_mb MB] [--builder_disk_mb MB] [--docker_compat] [--public]\",\n );\n }\n\n const cpus =\n parsed.values.cpus != null ? Number(parsed.values.cpus) : undefined;\n const memoryMb =\n parsed.values.memory != null ? Number(parsed.values.memory) : undefined;\n const diskMb =\n parsed.values.disk_mb != null ? Number(parsed.values.disk_mb) : undefined;\n const builderDiskMb =\n parsed.values.builder_disk_mb != null\n ? Number(parsed.values.builder_disk_mb)\n : undefined;\n if (cpus != null && !Number.isFinite(cpus)) {\n throw new Error(`Invalid --cpus value: ${parsed.values.cpus}`);\n }\n if (memoryMb != null && !Number.isInteger(memoryMb)) {\n throw new Error(`Invalid --memory value: ${parsed.values.memory}`);\n }\n if (diskMb != null && !Number.isInteger(diskMb)) {\n throw new Error(`Invalid --disk_mb value: ${parsed.values.disk_mb}`);\n }\n if (builderDiskMb != null && !Number.isInteger(builderDiskMb)) {\n throw new Error(\n `Invalid --builder_disk_mb value: ${parsed.values.builder_disk_mb}`,\n );\n }\n\n await createSandboxImage(\n dockerfilePath,\n {\n registeredName: parsed.values.name,\n cpus,\n memoryMb,\n diskMb,\n builderDiskMb,\n dockerCompat: parsed.values.docker_compat,\n isPublic: parsed.values.public,\n },\n { emit: ndjsonStdoutEmit, _allowPat: true },\n );\n}\n\nexport async function runImportSandboxImageCli(argv = process.argv.slice(2)) {\n const parsed = parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n name: { type: \"string\", short: \"n\" },\n cpus: { type: \"string\" },\n memory: { type: \"string\" },\n disk_mb: { type: \"string\" },\n builder_disk_mb: { type: \"string\" },\n docker_compat: { type: \"boolean\", default: false },\n public: { type: \"boolean\", default: false },\n },\n });\n\n const imageReference = parsed.positionals[0];\n if (!imageReference) {\n throw new Error(\n \"Usage: tensorlake-import-sandbox-image <image_reference> [--name NAME] [--cpus N] [--memory MB] [--disk_mb MB] [--builder_disk_mb MB] [--docker_compat] [--public]\",\n );\n }\n\n const cpus =\n parsed.values.cpus != null ? Number(parsed.values.cpus) : undefined;\n const memoryMb =\n parsed.values.memory != null ? Number(parsed.values.memory) : undefined;\n const diskMb =\n parsed.values.disk_mb != null ? Number(parsed.values.disk_mb) : undefined;\n const builderDiskMb =\n parsed.values.builder_disk_mb != null\n ? Number(parsed.values.builder_disk_mb)\n : undefined;\n if (cpus != null && !Number.isFinite(cpus)) {\n throw new Error(`Invalid --cpus value: ${parsed.values.cpus}`);\n }\n if (memoryMb != null && !Number.isInteger(memoryMb)) {\n throw new Error(`Invalid --memory value: ${parsed.values.memory}`);\n }\n if (diskMb != null && !Number.isInteger(diskMb)) {\n throw new Error(`Invalid --disk_mb value: ${parsed.values.disk_mb}`);\n }\n if (builderDiskMb != null && !Number.isInteger(builderDiskMb)) {\n throw new Error(\n `Invalid --builder_disk_mb value: ${parsed.values.builder_disk_mb}`,\n );\n }\n\n await importSandboxImage(\n imageReference,\n {\n registeredName: parsed.values.name,\n cpus,\n memoryMb,\n diskMb,\n builderDiskMb,\n dockerCompat: parsed.values.docker_compat,\n isPublic: parsed.values.public,\n },\n { emit: ndjsonStdoutEmit, _allowPat: true },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACAA,IACa,aAEA,SAEA,SACA,WACA,mBAGA,yBACA,aACA,kBACA;AAbb;AAAA;AAAA;AAAA;AACO,IAAM,cAAsB;AAE5B,IAAM,UACX,QAAQ,IAAI,sBAAsB;AAC7B,IAAM,UAAU,QAAQ,IAAI,sBAAsB;AAClD,IAAM,YAAY,QAAQ,IAAI,sBAAsB;AACpD,IAAM,oBACX,QAAQ,IAAI,gCAAgC;AAEvC,IAAM,0BAA0B;AAChC,IA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ileURLToPath","require","path","existsSync","DEFAULT_IMAGE_NAME"]}
1
+ {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/defaults.ts","../src/errors.ts","../src/sdk-timings.ts","../src/http.ts","../src/models.ts","../src/sse.ts","../src/cloud-client.ts","../src/image.ts","../lib/libc.cjs","../src/native-binding.ts","../src/sandbox-image.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","declare const __SDK_VERSION__: string;\nexport const SDK_VERSION: string = __SDK_VERSION__;\n\nexport const API_URL =\n process.env.TENSORLAKE_API_URL ?? \"https://api.tensorlake.ai\";\nexport const API_KEY = process.env.TENSORLAKE_API_KEY ?? undefined;\nexport const NAMESPACE = process.env.INDEXIFY_NAMESPACE ?? \"default\";\nexport const SANDBOX_PROXY_URL =\n process.env.TENSORLAKE_SANDBOX_PROXY_URL ?? \"https://sandbox.tensorlake.ai\";\n\nexport const DEFAULT_HTTP_TIMEOUT_MS = 300_000;\nexport const MAX_RETRIES = 3;\nexport const RETRY_BACKOFF_MS = 500;\nexport const RETRYABLE_STATUS_CODES = new Set([429, 502, 503, 504]);\n","/** Base exception for all sandbox-related errors. */\nexport class SandboxException extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SandboxException\";\n }\n}\n\n/** General sandbox operation error. */\nexport class SandboxError extends SandboxException {\n constructor(message: string) {\n super(message);\n this.name = \"SandboxError\";\n }\n}\n\n/**\n * Raised when the client cannot complete a request against the API server.\n *\n * The original transport error (typically undici's `TypeError: fetch failed`,\n * whose real reason — `ECONNREFUSED`, `UND_ERR_CONNECT_TIMEOUT`, `EMFILE`, … —\n * lives in `.cause`) is preserved on this error's {@link cause} for programmatic\n * inspection, and its full chain is folded into the message so it survives\n * wrappers that only forward `error.message`. No interpretation of the failure\n * (client vs server) is applied — the raw inner error is surfaced as-is so the\n * reader can judge.\n */\nexport class SandboxConnectionError extends SandboxError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(`Connection error: ${message}`);\n this.name = \"SandboxConnectionError\";\n if (options?.cause !== undefined) this.cause = options.cause;\n }\n}\n\n/**\n * Flatten an error and its `cause` chain into a single readable line, appending\n * each level's `code` when it is not already present in the message. undici\n * reports `fetch failed` at the top and the real reason one or more levels down\n * in `.cause`, so this surfaces the part that actually identifies the failure.\n *\n * @example \"fetch failed: connect ECONNREFUSED 10.0.0.1:443\"\n * @example \"fetch failed: Connect Timeout Error (UND_ERR_CONNECT_TIMEOUT)\"\n */\nexport function describeError(err: unknown): string {\n const parts: string[] = [];\n const seen = new Set<unknown>();\n let current: unknown = err;\n\n for (let depth = 0; depth < 6; depth++) {\n if (current == null || typeof current !== \"object\" || seen.has(current)) {\n break;\n }\n seen.add(current);\n const e = current as { message?: unknown; code?: unknown; cause?: unknown };\n const message = typeof e.message === \"string\" ? e.message.trim() : \"\";\n const code = typeof e.code === \"string\" ? e.code : undefined;\n\n let segment = message;\n if (code && (!message || !message.includes(code))) {\n segment = segment ? `${segment} (${code})` : code;\n }\n if (segment && !parts.includes(segment)) parts.push(segment);\n\n current = e.cause;\n }\n\n if (parts.length > 0) return parts.join(\": \");\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Raised when a sandbox is not found. */\nexport class SandboxNotFoundError extends SandboxError {\n readonly sandboxId: string;\n\n constructor(sandboxId: string) {\n super(`Sandbox not found: ${sandboxId}`);\n this.name = \"SandboxNotFoundError\";\n this.sandboxId = sandboxId;\n }\n}\n\n/** Raised when a sandbox pool is not found. */\nexport class PoolNotFoundError extends SandboxError {\n readonly poolId: string;\n\n constructor(poolId: string) {\n super(`Sandbox pool not found: ${poolId}`);\n this.name = \"PoolNotFoundError\";\n this.poolId = poolId;\n }\n}\n\n/** Raised when attempting to delete a pool that is in use. */\nexport class PoolInUseError extends SandboxError {\n readonly poolId: string;\n\n constructor(poolId: string, message?: string) {\n const base = `Cannot delete pool ${poolId}: pool is in use`;\n super(message ? `${base} - ${message}` : base);\n this.name = \"PoolInUseError\";\n this.poolId = poolId;\n }\n}\n\nexport function formatErrorDetails(errorDetails: unknown): string | undefined {\n if (errorDetails == null) return undefined;\n if (typeof errorDetails === \"string\") {\n const detail = errorDetails.trim();\n return detail || undefined;\n }\n if (Array.isArray(errorDetails)) {\n const parts = errorDetails\n .map((item) => formatErrorDetails(item))\n .filter((item): item is string => Boolean(item));\n return parts.length > 0 ? parts.join(\"; \") : JSON.stringify(errorDetails);\n }\n if (typeof errorDetails === \"object\") {\n for (const key of [\"message\", \"detail\", \"error\", \"reason\"]) {\n const value = (errorDetails as Record<string, unknown>)[key];\n if (typeof value === \"string\" && value.trim()) {\n return value.trim();\n }\n }\n return JSON.stringify(errorDetails);\n }\n return String(errorDetails);\n}\n\n/** Raised when the remote API returns an error. */\nexport class RemoteAPIError extends SandboxError {\n readonly statusCode: number;\n /** Original response body, retained for compatibility and diagnostics. */\n readonly responseMessage: string;\n readonly sandboxId?: string;\n /** Server reason, including unknown future reasons. */\n readonly reason?: string;\n readonly errorDetails?: unknown;\n\n constructor(statusCode: number, message: string) {\n let failure: Record<string, unknown> | undefined;\n try {\n const payload: unknown = JSON.parse(message);\n if (payload && typeof payload === \"object\" && !Array.isArray(payload)) {\n const record = payload as Record<string, unknown>;\n if (\n typeof record.sandbox_id === \"string\" &&\n record.sandbox_id.trim() &&\n (record.status === \"failed\" || record.status === \"terminated\")\n )\n failure = record;\n }\n } catch {\n // Non-JSON errors keep their existing message.\n }\n const sandboxId = failure?.sandbox_id as string | undefined;\n const rawReason = failure?.reason ?? failure?.termination_reason;\n const reason = typeof rawReason === \"string\" ? rawReason : undefined;\n const errorDetails = failure?.error_details;\n let displayMessage = message;\n if (failure) {\n displayMessage = `Sandbox ${sandboxId} ${failure.status}`;\n if (reason) displayMessage += ` (${reason})`;\n const detail = formatErrorDetails(errorDetails);\n if (detail) displayMessage += `: ${detail}`;\n if (!reason && !detail) displayMessage = message;\n }\n super(`API error (status ${statusCode}): ${displayMessage}`);\n this.sandboxId = sandboxId;\n this.reason = reason;\n this.errorDetails = errorDetails;\n this.name = \"RemoteAPIError\";\n this.statusCode = statusCode;\n this.responseMessage = message;\n }\n}\n\n/** Raised when request output is fetched before the request has completed. */\nexport class RequestNotFinishedError extends Error {\n constructor() {\n super(\"Request has not finished yet\");\n this.name = \"RequestNotFinishedError\";\n }\n}\n\n/** Raised when a request completed unsuccessfully. */\nexport class RequestFailedError extends Error {\n readonly failure: string;\n\n constructor(failure: string) {\n super(`Request failed: ${failure}`);\n this.name = \"RequestFailedError\";\n this.failure = failure;\n }\n}\n\n/** Raised when a request surfaced an application-level error. */\nexport class RequestExecutionError extends Error {\n readonly functionName?: string;\n\n constructor(message: string, functionName?: string) {\n super(\n functionName ? `Request error in ${functionName}: ${message}` : message,\n );\n this.name = \"RequestExecutionError\";\n this.functionName = functionName;\n }\n}\n","const SDK_TIMINGS_ENV_VAR = \"TENSORLAKE_SDK_TIMINGS\";\nconst SDK_TIMING_PAYLOADS_ENV_VAR = \"TENSORLAKE_SDK_TIMING_PAYLOADS\";\n\nexport type SdkTimingFields = Record<string, string | number | boolean | null | undefined>;\n\nexport function sdkTimingsEnabled(): boolean {\n const value = process.env[SDK_TIMINGS_ENV_VAR];\n return value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\nexport function sdkTimingPayloadsEnabled(): boolean {\n const value = process.env[SDK_TIMING_PAYLOADS_ENV_VAR];\n return value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\nexport function nowMs(): number {\n return performance.now();\n}\n\nexport function logSdkTiming(\n op: string,\n phase: string,\n startedAt: number,\n fields: SdkTimingFields = {},\n): void {\n if (!sdkTimingsEnabled()) return;\n logSdkTimingEvent(op, phase, {\n ...fields,\n duration_ms: Math.round((nowMs() - startedAt) * 100) / 100,\n });\n}\n\nexport function logSdkTimingEvent(\n op: string,\n phase: string,\n fields: SdkTimingFields = {},\n): void {\n if (!sdkTimingsEnabled()) return;\n\n const parts = [\n \"[tensorlake:sdk-timing]\",\n `op=${op}`,\n `phase=${phase}`,\n ];\n\n for (const [key, value] of Object.entries(fields)) {\n if (value == null) continue;\n parts.push(`${key}=${formatSdkTimingValue(value)}`);\n }\n\n console.error(parts.join(\" \"));\n}\n\nfunction formatSdkTimingValue(value: string | number | boolean): string {\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (/^[A-Za-z0-9_./:@-]+$/.test(value)) {\n return value;\n }\n return JSON.stringify(value);\n}\n","import {\n Agent,\n fetch as undiciFetch,\n setGlobalDispatcher,\n type BodyInit as UndiciBodyInit,\n} from \"undici\";\nimport * as defaults from \"./defaults.js\";\nimport {\n describeError,\n PoolInUseError,\n PoolNotFoundError,\n RemoteAPIError,\n SandboxConnectionError,\n SandboxNotFoundError,\n} from \"./errors.js\";\nimport {\n nowMs,\n logSdkTimingEvent,\n logSdkTiming,\n sdkTimingPayloadsEnabled,\n} from \"./sdk-timings.js\";\n\nconst REQUEST_TIMEOUT_HEADER = \"X-Tensorlake-Request-Timeout-Ms\";\n\nexport interface HttpClientOptions {\n baseUrl: string;\n apiKey?: string;\n organizationId?: string;\n projectId?: string;\n hostHeader?: string;\n sandboxIdHeader?: string;\n routingHint?: string;\n maxRetries?: number;\n retryBackoffMs?: number;\n timeoutMs?: number | null;\n}\n\nsetGlobalDispatcher(\n new Agent({\n keepAliveTimeout: 60_000,\n allowH2: true,\n }),\n);\n\n\ntype RequestBody = BodyInit | Uint8Array | ArrayBuffer;\n\nexport interface HttpRequestOptions {\n body?: RequestBody | null;\n headers?: Record<string, string>;\n json?: unknown;\n signal?: AbortSignal;\n allowHttpErrors?: boolean;\n retryableStatusCodes?: Set<number>;\n allowedErrorStatusCodes?: Set<number>;\n}\n\n/**\n * The return value of every SDK operation. Carries the W3C `trace_id` so callers\n * can correlate a specific request with its server-side spans in Datadog APM or\n * any other OTEL-compatible backend.\n *\n * Because this is an intersection type, all properties of `T` are accessible\n * directly — existing code that ignores `traceId` continues to compile and run\n * unchanged.\n *\n * @example\n * const sandbox = await client.createSandbox(req);\n * console.log(sandbox.id); // existing field — unchanged\n * console.log(sandbox.traceId); // new: look this up in Datadog APM\n */\nexport type Traced<T> = T & { readonly traceId: string };\n\nfunction withTraceId<T>(value: T, traceId: string): Traced<T> {\n if (value == null) {\n return { traceId } as unknown as Traced<T>;\n }\n return Object.assign(value as any, { traceId }) as Traced<T>;\n}\n\n/**\n * Internal HTTP client with retry logic, auth headers, and error mapping.\n *\n * Uses native `fetch`. Retries on transient status codes (429, 502, 503, 504)\n * with exponential backoff.\n */\nexport class HttpClient {\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n private readonly maxRetries: number;\n private readonly retryBackoffMs: number;\n private readonly timeoutMs: number | null;\n private abortController: AbortController | null = null;\n\n constructor(options: HttpClientOptions) {\n const url = options.baseUrl;\n this.baseUrl = url.endsWith(\"/\") ? url.slice(0, -1) : url;\n this.maxRetries = options.maxRetries ?? defaults.MAX_RETRIES;\n this.retryBackoffMs = options.retryBackoffMs ?? defaults.RETRY_BACKOFF_MS;\n this.timeoutMs = options.timeoutMs === undefined\n ? defaults.DEFAULT_HTTP_TIMEOUT_MS\n : options.timeoutMs;\n\n this.headers = {\n \"User-Agent\": `tensorlake-typescript-sdk/${defaults.SDK_VERSION}`,\n };\n if (this.timeoutMs != null) {\n this.headers[REQUEST_TIMEOUT_HEADER] = String(this.timeoutMs);\n }\n if (options.apiKey) {\n this.headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n if (options.organizationId) {\n this.headers[\"X-Forwarded-Organization-Id\"] = options.organizationId;\n }\n if (options.projectId) {\n this.headers[\"X-Forwarded-Project-Id\"] = options.projectId;\n }\n if (options.hostHeader) {\n this.headers[\"Host\"] = options.hostHeader;\n }\n if (options.sandboxIdHeader) {\n this.headers[\"X-Tensorlake-Sandbox-Id\"] = options.sandboxIdHeader;\n }\n if (options.routingHint) {\n this.headers[\"X-Tensorlake-Route-Hint\"] = options.routingHint;\n }\n }\n\n close(): void {\n this.abortController?.abort();\n this.abortController = null;\n }\n\n /** Make a JSON request, returning the parsed response body. */\n async requestJson<T>(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n retryableStatusCodes?: Set<number>;\n allowedErrorStatusCodes?: Set<number>;\n allowHttpErrors?: boolean;\n },\n ): Promise<Traced<T>> {\n const response = await this.requestResponse(method, path, {\n json: options?.body,\n headers: options?.headers,\n signal: options?.signal,\n retryableStatusCodes: options?.retryableStatusCodes,\n allowedErrorStatusCodes: options?.allowedErrorStatusCodes,\n allowHttpErrors: options?.allowHttpErrors,\n });\n const text = await response.text();\n const data = (text ? JSON.parse(text) : undefined) as T;\n return withTraceId(data, response.traceId);\n }\n\n /** Make a request returning raw bytes. */\n async requestBytes(\n method: string,\n path: string,\n options?: {\n body?: RequestBody | null;\n contentType?: string;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n },\n ): Promise<Traced<Uint8Array>> {\n const headers = { ...(options?.headers ?? {}) };\n if (options?.contentType) {\n headers[\"Content-Type\"] = options.contentType;\n }\n\n const response = await this.requestResponse(method, path, {\n body: options?.body,\n headers,\n signal: options?.signal,\n });\n const buffer = await response.arrayBuffer();\n return withTraceId(new Uint8Array(buffer), response.traceId);\n }\n\n /** Make a request and return the response body as an SSE stream. */\n async requestStream(\n method: string,\n path: string,\n options?: { signal?: AbortSignal; json?: unknown },\n ): Promise<Traced<ReadableStream<Uint8Array>>> {\n const response = await this.requestResponse(method, path, {\n json: options?.json,\n headers: { Accept: \"text/event-stream\" },\n signal: options?.signal,\n });\n if (!response.body) {\n throw new RemoteAPIError(\n response.status,\n \"No response body for SSE stream\",\n );\n }\n return withTraceId(response.body, response.traceId);\n }\n\n /** Make a request and return the raw Response. */\n async requestResponse(\n method: string,\n path: string,\n options?: HttpRequestOptions,\n ): Promise<Traced<Response>> {\n const headers = {\n ...this.headers,\n ...(options?.headers ?? {}),\n };\n const hasJsonBody = options?.json !== undefined;\n if (hasJsonBody && !hasHeader(headers, \"Content-Type\")) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n const body = hasJsonBody\n ? JSON.stringify(options?.json)\n : normalizeRequestBody(options?.body);\n\n const { response, traceId } = await this.doFetch(\n method,\n path,\n body,\n headers,\n options?.signal,\n options?.allowHttpErrors ?? false,\n options?.retryableStatusCodes ?? defaults.RETRYABLE_STATUS_CODES,\n options?.allowedErrorStatusCodes ?? new Set(),\n );\n return withTraceId(response, traceId);\n }\n\n private static makeTraceparent(): { traceparent: string; traceId: string } {\n const randomHex = (bytes: number) =>\n Array.from(crypto.getRandomValues(new Uint8Array(bytes)))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n const traceId = randomHex(16);\n const spanId = randomHex(8);\n return { traceparent: `00-${traceId}-${spanId}-01`, traceId };\n }\n\n private async doFetch(\n method: string,\n path: string,\n body: UndiciBodyInit | undefined,\n headers: Record<string, string>,\n signal?: AbortSignal,\n allowHttpErrors = false,\n retryableStatusCodes: Set<number> = defaults.RETRYABLE_STATUS_CODES,\n allowedErrorStatusCodes: Set<number> = new Set(),\n ): Promise<{ response: Response; traceId: string }> {\n const url = `${this.baseUrl}${path}`;\n const { traceparent, traceId } = HttpClient.makeTraceparent();\n headers[\"traceparent\"] = traceparent;\n let lastError: Error | undefined;\n const operationStart = nowMs();\n const timingPath = sdkTimingPayloadsEnabled() ? path : stripPathPayload(path);\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n if (attempt > 0) {\n const delay = this.retryBackoffMs * Math.pow(2, attempt - 1);\n logSdkTimingEvent(\"http.request\", \"retry_sleep_start\", {\n method,\n path: timingPath,\n attempt,\n delay_ms: delay,\n server_trace_id: traceId,\n });\n await sleep(delay);\n }\n\n this.abortController = new AbortController();\n // Track whether *our* deadline fired, so we can tell a client-imposed\n // timeout apart from a network rejection or a caller-initiated abort.\n let timedOut = false;\n const timeoutId = this.timeoutMs == null\n ? null\n : setTimeout(() => {\n timedOut = true;\n this.abortController?.abort();\n }, this.timeoutMs);\n\n // Combine external signal with internal timeout\n const combinedSignal = signal\n ? anySignal([signal, this.abortController.signal])\n : this.abortController.signal;\n\n const attemptStart = nowMs();\n try {\n const response = (await undiciFetch(url, {\n method,\n headers,\n body,\n signal: combinedSignal,\n })) as unknown as Response;\n\n if (timeoutId != null) clearTimeout(timeoutId);\n logSdkTiming(\"http.request\", \"headers\", attemptStart, {\n method,\n path: timingPath,\n status: response.status,\n attempt,\n server_trace_id: traceId,\n });\n\n if (response.ok) {\n logSdkTiming(\"http.request\", \"complete\", operationStart, {\n method,\n path: timingPath,\n status: response.status,\n attempts: attempt + 1,\n server_trace_id: traceId,\n });\n return { response, traceId };\n }\n\n // Check if retryable\n if (\n retryableStatusCodes.has(response.status) &&\n attempt < this.maxRetries\n ) {\n lastError = new RemoteAPIError(\n response.status,\n await response.text().catch(() => \"\"),\n );\n logSdkTimingEvent(\"http.request\", \"retryable_status\", {\n method,\n path: timingPath,\n status: response.status,\n attempt,\n server_trace_id: traceId,\n });\n continue;\n }\n\n if (allowHttpErrors || allowedErrorStatusCodes.has(response.status)) {\n logSdkTiming(\"http.request\", \"complete\", operationStart, {\n method,\n path: timingPath,\n status: response.status,\n attempts: attempt + 1,\n server_trace_id: traceId,\n });\n return { response, traceId };\n }\n\n // Non-retryable error — throw mapped error\n const errorBody = await response.text().catch(() => \"\");\n throwMappedError(response.status, errorBody, path);\n } catch (err) {\n if (timeoutId != null) clearTimeout(timeoutId);\n\n if (\n err instanceof RemoteAPIError ||\n err instanceof SandboxNotFoundError ||\n err instanceof PoolNotFoundError ||\n err instanceof PoolInUseError\n ) {\n throw err;\n }\n\n // A caller-supplied signal fired (and it wasn't our own deadline).\n if (signal?.aborted && !timedOut) {\n throw new SandboxConnectionError(\"request aborted by caller\", {\n cause: err,\n });\n }\n\n // Network / timeout error\n lastError = err instanceof Error ? err : new Error(String(err));\n logSdkTiming(\"http.request\", \"error\", attemptStart, {\n method,\n path: timingPath,\n attempt,\n server_trace_id: traceId,\n error: timedOut ? `request timed out after ${this.timeoutMs}ms` : describeError(err),\n });\n\n if (attempt >= this.maxRetries) {\n // Surface the real inner cause; for our own deadline, say so plainly.\n const detail = timedOut\n ? `request timed out after ${this.timeoutMs}ms`\n : describeError(err);\n throw new SandboxConnectionError(detail, { cause: err });\n }\n }\n }\n\n throw new SandboxConnectionError(\n lastError ? describeError(lastError) : \"request failed\",\n { cause: lastError },\n );\n }\n}\n\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n const lowered = name.toLowerCase();\n return Object.keys(headers).some((key) => key.toLowerCase() === lowered);\n}\n\nfunction normalizeRequestBody(\n body?: RequestBody | null,\n): UndiciBodyInit | undefined {\n if (body == null) {\n return undefined;\n }\n if (body instanceof Uint8Array) {\n return Uint8Array.from(body).buffer as ArrayBuffer;\n }\n return body as UndiciBodyInit;\n}\n\nfunction stripPathPayload(path: string): string {\n const queryStart = path.search(/[?#]/);\n return queryStart === -1 ? path : path.slice(0, queryStart);\n}\n\n/** Map HTTP status codes to specific error types. */\nfunction throwMappedError(status: number, body: string, path: string): never {\n let message = body;\n try {\n const parsed = JSON.parse(body);\n if (parsed.message) message = parsed.message;\n else if (parsed.error) message = parsed.error;\n } catch {\n // use raw body\n }\n\n if (status === 404) {\n // Determine entity type from path\n if (path.includes(\"sandbox-pools\") || path.includes(\"pools\")) {\n const match = path.match(/sandbox-pools\\/([^/]+)/);\n if (match) throw new PoolNotFoundError(match[1]);\n }\n if (path.includes(\"sandboxes\")) {\n const match = path.match(/sandboxes\\/([^/]+)/);\n if (match) throw new SandboxNotFoundError(match[1]);\n }\n throw new RemoteAPIError(404, message);\n }\n\n if (status === 409) {\n if (path.includes(\"sandbox-pools\") || path.includes(\"pools\")) {\n const match = path.match(/sandbox-pools\\/([^/]+)/);\n if (match) throw new PoolInUseError(match[1], message);\n }\n }\n\n throw new RemoteAPIError(status, message);\n}\n\n/** Combine multiple AbortSignals into one that aborts when any fires. */\nfunction anySignal(signals: AbortSignal[]): AbortSignal {\n const controller = new AbortController();\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n return controller.signal;\n }\n signal.addEventListener(\"abort\", () => controller.abort(signal.reason), {\n once: true,\n });\n }\n return controller.signal;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","// --- Enums ---\n\nexport enum SandboxStatus {\n PENDING = \"pending\",\n RUNNING = \"running\",\n SNAPSHOTTING = \"snapshotting\",\n SUSPENDING = \"suspending\",\n SUSPENDED = \"suspended\",\n TERMINATED = \"terminated\",\n TIMEOUT = \"timeout\",\n /** Terminal status used by blocking create/claim responses. */\n FAILED = \"failed\",\n}\n\nexport enum SnapshotStatus {\n IN_PROGRESS = \"in_progress\",\n LOCAL_READY = \"local_ready\",\n COMPLETED = \"completed\",\n FAILED = \"failed\",\n}\n\n/**\n * Snapshot type for sandbox snapshot creation.\n *\n * - `\"memory\"`: Capture VM memory + filesystem state. Sandboxes restored\n * from this snapshot warm-restore VM memory.\n * - `\"filesystem\"`: Capture filesystem state only. Sandboxes restored from\n * this snapshot cold-boot from the snapshot tarball instead of warm-\n * restoring VM state. Use this for sandbox image builds so that the\n * restored sandbox bypasses Firecracker's overlay-path constraints.\n */\nexport type SnapshotType = \"memory\" | \"filesystem\";\n\n/**\n * Checkpoint type for {@link Sandbox.checkpoint}.\n *\n * - `\"memory\"`: Capture VM memory + filesystem state. Sandboxes restored\n * from this checkpoint warm-restore VM memory and running processes.\n * - `\"filesystem\"`: Capture filesystem state only. Sandboxes restored from\n * this checkpoint cold-boot from the snapshot tarball.\n */\nexport type CheckpointType = \"memory\" | \"filesystem\";\n\nexport type SnapshotWaitCondition = \"local_ready\" | \"completed\";\n\nexport enum ProcessStatus {\n RUNNING = \"running\",\n EXITED = \"exited\",\n SIGNALED = \"signaled\",\n OOM_KILLED = \"oom_killed\",\n}\n\nexport enum StdinMode {\n CLOSED = \"closed\",\n PIPE = \"pipe\",\n}\n\nexport enum OutputMode {\n CAPTURE = \"capture\",\n DISCARD = \"discard\",\n}\n\nexport enum ContainerState {\n IDLE = \"Idle\",\n RUNNING = \"Running\",\n}\n\n// --- Resource / Network ---\n\nexport interface ContainerResourcesInfo {\n cpus: number;\n memoryMb: number;\n ephemeralDiskMb: number;\n}\n\n/** GPU models supported by the sandbox scheduler. */\nexport type GpuModel =\n | \"A100-40GB\"\n | \"A100-80GB\"\n | \"H100\"\n | \"T4\"\n | \"A6000\"\n | \"A10\";\n\n/** A homogeneous GPU allocation for a sandbox. */\nexport interface GpuRequest {\n count: number;\n model: GpuModel;\n}\n\nexport interface GPUResources {\n count: number;\n model: string;\n}\n\n/**\n * Egress network access control policy for a sandbox.\n *\n * `denyOut` takes precedence over `allowOut`: a destination matched by both is\n * blocked. Entries may be IPv4 addresses, CIDR ranges, or DNS hostnames;\n * hostname rules are followed across DNS changes. The policy can be changed on\n * a running sandbox via `Sandbox.update({ network })` (pass `null` to clear).\n */\nexport interface NetworkConfig {\n allowInternetAccess: boolean;\n allowOut: string[];\n denyOut: string[];\n}\n\n/**\n * One file system mounted into a sandbox at an absolute guest path.\n *\n * `fileSystemId` is the Artifact Storage file-system name created with\n * `tl fs create <name>` and `mountPath` is an absolute, unique guest path\n * (e.g. `/mnt/skills`).\n *\n * `readOnly` and `prefetch` are optional mount modes; they are sent on the\n * wire only when `true` (older servers reject unknown mount fields, so\n * `false` is expressed by omission).\n *\n * `snapshotId` pins the mount to a specific filesystem snapshot. A pinned\n * mount must also set `readOnly: true` (the server rejects a writable pin\n * with HTTP 400). It is sent only when set, for the same compatibility\n * reason as the mount modes.\n *\n * `owner` presents the mounted files as owned by a guest user: `NAME`,\n * `UID`, `NAME:GROUP`, or `UID:GID` (e.g. `\"agent\"` or `\"1001:1001\"`),\n * resolved against the sandbox image's own user database when the mount\n * attaches. Unset keeps the image default (the baked `tl-user` account when\n * the image has one, otherwise root). It is sent only when set, for the\n * same compatibility reason as the mount modes.\n */\nexport interface FileSystemMount {\n fileSystemId: string;\n mountPath: string;\n /** Mount the file system read-only. */\n readOnly?: boolean;\n /** Eagerly download the file system's contents. */\n prefetch?: boolean;\n /** Pin the mount to a specific filesystem snapshot (requires `readOnly`). */\n snapshotId?: string;\n /** Present the mounted files as owned by this guest user spec. */\n owner?: string;\n}\n\n/** Optional mount modes for attaching a file system to a running sandbox. */\nexport interface AttachFileSystemOptions {\n /** Mount the file system read-only. */\n readOnly?: boolean;\n /** Eagerly download the file system's contents. */\n prefetch?: boolean;\n /** Pin the mount to a specific filesystem snapshot (requires `readOnly`). */\n snapshotId?: string;\n /** Present the mounted files as owned by this guest user spec. */\n owner?: string;\n}\n\nexport interface ClaimSandboxOptions {\n /** File systems to mount before the claimed sandbox is reported as running. */\n fileSystems?: FileSystemMount[];\n}\n\n// --- Sandbox lifecycle ---\n\nexport interface CreateSandboxOptions {\n /** Optional sandbox image name. GPU sandboxes require a CAS image; when omitted with a GPU request, Tensorlake uses the server's configured GPU default. */\n image?: string;\n /** CPU count. Defaults to 1 for fresh creates; snapshot restores inherit it when omitted. */\n cpus?: number;\n /** Memory in MB. Defaults to 1024 for fresh creates; snapshot restores inherit it when omitted. */\n memoryMb?: number;\n /** Root disk size in megabytes. When omitted, the server uses its default disk size. */\n diskMb?: number;\n /** Number of GPUs to allocate. Defaults to A10 unless gpuModel is set. GPU sandboxes require a CAS image. */\n gpus?: number;\n /** GPU model to allocate. The string arm preserves compatibility with existing callers; values are validated at runtime. */\n gpuModel?: GpuModel | (string & {});\n /** Typed GPU model and count request. Cannot be combined with gpus or gpuModel. */\n gpu?: GpuRequest;\n timeoutSecs?: number;\n entrypoint?: string[];\n allowInternetAccess?: boolean;\n allowOut?: string[];\n denyOut?: string[];\n snapshotId?: string;\n /** Optional name for the sandbox. Named sandboxes support suspend/resume. When absent the sandbox is ephemeral. */\n name?: string;\n /** File systems to mount on fresh creation or warm-pool claim, each at its own absolute, unique guest mount path. */\n fileSystems?: FileSystemMount[];\n}\n\nexport interface UpdateSandboxOptions {\n /** New name for the sandbox. Naming an ephemeral sandbox enables suspend/resume. */\n name?: string;\n /** Whether exposed user ports should be reachable without TensorLake auth. */\n allowUnauthenticatedAccess?: boolean;\n /** User ports that should be routable through the sandbox proxy. Port 9501 is reserved. */\n exposedPorts?: number[];\n /**\n * Egress network policy for the running sandbox, applied to the live VM's\n * firewall in one atomic swap. Omit to keep the current policy, set to\n * replace it, or pass `null` to clear it to unrestricted egress.\n */\n network?: NetworkConfig | null;\n}\n\nexport interface CreateSandboxResponse {\n sandboxId: string;\n status: SandboxStatus;\n reason?: string;\n routingHint?: string;\n ingressEndpoint?: string;\n sandboxUrl?: string;\n name?: string | null;\n terminationReason?: string;\n errorDetails?: unknown;\n}\n\nexport interface CopySandboxOptions {\n /** Number of running copies to create. Defaults to 1. */\n times?: number;\n /** Per-request timeout in seconds for the blocking live-copy request. */\n requestTimeout?: number;\n}\n\nexport interface CopiedSandboxResponse {\n sandboxId: string;\n /** Raw server status. Partial copy responses can include statuses such as `\"failed\"`. */\n status: string;\n reason?: string;\n routingHint?: string;\n ingressEndpoint?: string;\n sandboxUrl?: string;\n name?: string | null;\n terminationReason?: string;\n errorDetails?: unknown;\n}\n\nexport interface CopySandboxResponse {\n sourceSandboxId: string;\n sandboxes: CopiedSandboxResponse[];\n}\n\nexport interface SandboxInfo {\n sandboxId: string;\n namespace: string;\n status: SandboxStatus;\n /** Resolved sandbox image name. */\n image?: string;\n resources: ContainerResourcesInfo;\n timeoutSecs?: number;\n entrypoint?: string[];\n network?: NetworkConfig;\n poolId?: string;\n outcome?: string;\n terminationReason?: string;\n errorDetails?: unknown;\n createdAt?: Date;\n terminatedAt?: Date;\n name?: string;\n allowUnauthenticatedAccess?: boolean;\n exposedPorts?: number[];\n ingressEndpoint?: string;\n sandboxUrl?: string;\n routingHint?: string;\n /** File systems currently mounted into the sandbox, each at its own guest mount path. Empty when none are mounted. */\n fileSystems?: FileSystemMount[];\n}\n\nexport interface SandboxPortAccess {\n allowUnauthenticatedAccess: boolean;\n exposedPorts: number[];\n ingressEndpoint?: string;\n sandboxUrl?: string;\n}\n\n/** Sandbox information plus the archival timestamp. */\nexport interface ArchivedSandboxInfo extends SandboxInfo {\n archivedAt: Date;\n}\n\n/** Pagination params for `listArchivedSandboxes`. */\nexport interface ListArchivedSandboxesOptions {\n limit?: number;\n /** Base64-encoded pagination cursor returned by a prior call. */\n cursor?: string;\n /** Pagination direction. */\n direction?: \"forward\" | \"backward\";\n}\n\nexport interface ListArchivedSandboxesResponse {\n sandboxes: ArchivedSandboxInfo[];\n prevCursor?: string;\n nextCursor?: string;\n}\n\n// --- Snapshots ---\n\nexport interface CreateSnapshotResponse {\n snapshotId: string;\n status: SnapshotStatus;\n}\n\nexport interface SnapshotInfo {\n snapshotId: string;\n namespace: string;\n sandboxId: string;\n baseImage: string;\n status: SnapshotStatus;\n snapshotType?: SnapshotType;\n error?: string;\n snapshotUri?: string;\n snapshotFormatVersion?: string;\n sizeBytes?: number;\n rootfsDiskBytes?: number;\n createdAt?: Date;\n}\n\nexport interface SnapshotOptions {\n /**\n * Optional snapshot type. When omitted the server picks its default. Use\n * `\"filesystem\"` for snapshots intended for sandbox image builds so that\n * restored sandboxes cold-boot.\n */\n snapshotType?: SnapshotType;\n}\n\nexport interface SnapshotAndWaitOptions extends SnapshotOptions {\n timeout?: number;\n pollInterval?: number;\n /** Defaults to `\"local_ready\"`, which is enough to resume from a snapshot. */\n waitUntil?: SnapshotWaitCondition;\n}\n\n// --- Persisted sandbox logs ---\n\nexport type SandboxLogLevel =\n \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\" | \"fatal\";\n\nexport interface GetSandboxLogsOptions {\n levels?: SandboxLogLevel[];\n processIds?: string[];\n nextToken?: string;\n head?: number;\n tail?: number;\n body?: string;\n}\n\nexport interface SandboxLogSignal {\n timestamp: number;\n uuid: string;\n namespace: string;\n application: string;\n sandboxId?: string;\n resourceAttributes: Array<[string, string]>;\n body: string;\n logAttributes: string;\n allocations?: string[];\n functionRuns?: string[];\n level?: number;\n retention?: number;\n}\n\nexport interface SandboxLogsResponse {\n logs: SandboxLogSignal[];\n nextToken?: string;\n}\n\nexport interface SandboxProcessLogFilter {\n processId: string;\n processPid: string;\n processCommand: string;\n processManagedId: string;\n processManagedName: string;\n firstSeen: number;\n lastSeen: number;\n logCount: number;\n}\n\nexport interface SandboxProcessLogFiltersResponse {\n processes: SandboxProcessLogFilter[];\n}\n\n// --- Pools ---\n\nexport interface CreatePoolOptions {\n /** Sandbox image name, such as `tensorlake/ubuntu-minimal` or a registered Sandbox Image. */\n image: string;\n cpus?: number;\n memoryMb?: number;\n ephemeralDiskMb?: number;\n timeoutSecs?: number;\n entrypoint?: string[];\n maxContainers?: number;\n warmContainers?: number;\n /** Network policy for each container. Can be replaced later via updatePool. */\n network?: NetworkConfig;\n}\n\nexport interface UpdatePoolOptions {\n /**\n * Network policy for each container. Omit to keep the pool's current policy,\n * set to replace it, or pass `null` to remove it (unclaimed warm containers\n * are recycled onto the new policy).\n */\n network?: NetworkConfig | null;\n /** Sandbox image name, such as `tensorlake/ubuntu-minimal` or a registered Sandbox Image. */\n image: string;\n cpus?: number;\n memoryMb?: number;\n ephemeralDiskMb?: number;\n timeoutSecs?: number;\n entrypoint?: string[];\n maxContainers?: number;\n warmContainers?: number;\n}\n\nexport interface CreateSandboxPoolResponse {\n poolId: string;\n namespace: string;\n}\n\nexport interface PoolContainerInfo {\n id: string;\n state: string;\n sandboxId?: string;\n executorId: string;\n}\n\nexport interface SandboxPoolInfo {\n poolId: string;\n namespace: string;\n /** Sandbox image name backing the pool. */\n image: string;\n resources: ContainerResourcesInfo;\n timeoutSecs: number;\n entrypoint?: string[];\n maxContainers?: number;\n warmContainers?: number;\n /** The network policy that applies to each container in the pool. */\n networkPolicy?: NetworkConfig;\n containers?: PoolContainerInfo[];\n createdAt?: Date;\n updatedAt?: Date;\n}\n\n// --- Process management ---\n\nexport interface ProcessUserSpec {\n name?: string;\n uid?: number;\n gid?: number;\n}\n\nexport type ProcessUser = string | ProcessUserSpec;\n\nexport type RestartPolicy = \"never\" | \"on_failure\" | \"always\";\n\nexport interface RestartPolicyConfig {\n policy?: RestartPolicy;\n maxRestarts?: number;\n initialBackoffMs?: number;\n maxBackoffMs?: number;\n}\n\nexport type ProcessHealthCheckType = \"http\" | \"tcp\";\n\nexport interface ProcessHealthCheck {\n type: ProcessHealthCheckType;\n port: number;\n path?: string;\n initialDelayMs?: number;\n intervalMs?: number;\n timeoutMs?: number;\n failureThreshold?: number;\n}\n\nexport type ManagedProcessStatus =\n \"starting\" | \"running\" | \"backing_off\" | \"stopped\";\n\nexport type ManagedProcessHealthStatus =\n \"disabled\" | \"starting\" | \"healthy\" | \"unhealthy\";\n\nexport interface ManagedProcessExit {\n exitCode?: number;\n signal?: number;\n oomKilled: boolean;\n endedAt: Date;\n}\n\n/**\n * Managed-process metadata embedded into {@link ProcessInfo}.\n *\n * A managed process is addressable by either its current PID or, if a `name` was given at\n * creation, that name (process APIs accept a PID or process name). `id` is a stable\n * daemon-local identifier: it equals `name` when one was set, otherwise a daemon-assigned\n * opaque id (the process is then addressable only by PID, not by `id`).\n */\nexport interface ManagedProcessInfo {\n id: string;\n name?: string;\n status: ManagedProcessStatus;\n restartCount: number;\n restart: RestartPolicyConfig;\n healthCheck?: ProcessHealthCheck;\n healthStatus: ManagedProcessHealthStatus;\n consecutiveHealthFailures: number;\n lastExit?: ManagedProcessExit;\n lastError?: string;\n nextRestartAt?: Date;\n}\n\nexport interface StartProcessOptions {\n args?: string[];\n env?: Record<string, string>;\n workingDir?: string;\n stdinMode?: StdinMode;\n stdoutMode?: OutputMode;\n stderrMode?: OutputMode;\n user?: ProcessUser;\n /**\n * Optional managed-process name. Supplying this opts into managed process behavior, and\n * lets the process be addressed by this name (in addition to its PID) in\n * `getProcess`/`killProcess`/`sendSignal`/etc. — useful because a managed process's PID\n * changes when it restarts. May contain any characters except `/` and must not be all\n * digits (numeric strings are reserved for PID addressing). If omitted, the daemon assigns\n * an opaque id (`ManagedProcessInfo.id`) and the process is addressable only by its current PID.\n */\n name?: string;\n /** Optional restart behavior. Supplying this opts into managed process behavior. */\n restart?: RestartPolicyConfig;\n /** Optional HTTP/TCP health check. Supplying this opts into managed process behavior. */\n healthCheck?: ProcessHealthCheck;\n}\n\nexport interface ProcessInfo {\n handle?: number;\n pid: number;\n status: ProcessStatus;\n exitCode?: number;\n signal?: number;\n stdinWritable: boolean;\n command: string;\n args: string[];\n startedAt: Date;\n endedAt?: Date;\n managed?: ManagedProcessInfo;\n}\n\nexport interface SendSignalResponse {\n success: boolean;\n}\n\nexport interface OutputResponse {\n pid: number;\n lines: string[];\n lineCount: number;\n}\n\nexport interface OutputEvent {\n line: string;\n timestamp: Date;\n stream?: string;\n}\n\n// --- Run ---\n\nexport interface RunOptions {\n args?: string[];\n env?: Record<string, string>;\n workingDir?: string;\n timeout?: number;\n user?: ProcessUser;\n}\n\nexport interface CommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n// --- File operations ---\n\nexport interface DirectoryEntry {\n name: string;\n isDir: boolean;\n size?: number;\n modifiedAt?: Date;\n}\n\nexport interface ListDirectoryResponse {\n path: string;\n entries: DirectoryEntry[];\n}\n\n// --- PTY ---\n\nexport interface CreatePtySessionOptions {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n workingDir?: string;\n rows?: number;\n cols?: number;\n}\n\nexport interface PtySessionInfo {\n sessionId: string;\n token: string;\n}\n\n// --- Health ---\n\nexport interface HealthResponse {\n healthy: boolean;\n}\n\nexport interface DaemonInfo {\n version: string;\n uptimeSecs: number;\n runningProcesses: number;\n totalProcesses: number;\n}\n\n// --- Client options ---\n\nexport interface SandboxClientOptions {\n apiUrl?: string;\n apiKey?: string;\n organizationId?: string;\n projectId?: string;\n namespace?: string;\n maxRetries?: number;\n retryBackoffMs?: number;\n /** Total HTTP request timeout in seconds. Default: 300. */\n requestTimeout?: number;\n /** @deprecated Use requestTimeout. Total HTTP request timeout in milliseconds. */\n timeoutMs?: number;\n}\n\nexport interface SandboxOptions {\n sandboxId: string;\n /**\n * Explicit sandbox proxy base URL. Direct `new Sandbox(...)` construction\n * requires this; `Sandbox.connect()` and `SandboxClient.connect()` normally\n * resolve the server-returned `sandboxUrl`.\n */\n proxyUrl?: string;\n /** @internal Real caller/env proxy override, distinct from an internally selected proxyUrl. */\n explicitProxyUrl?: string;\n apiKey?: string;\n organizationId?: string;\n projectId?: string;\n routingHint?: string;\n resolveProxyInfo?: (\n identifier: string,\n ) => Promise<SandboxInfo & { readonly traceId: string }>;\n /** Optional total HTTP request timeout in seconds for sandbox proxy operations. Omit for no total proxy timeout. */\n requestTimeout?: number;\n /** @deprecated Use requestTimeout. Optional total HTTP request timeout in milliseconds for sandbox proxy operations. */\n timeoutMs?: number;\n /**\n * @internal Shared Rust-backed lifecycle client. When provided, the proxy\n * client is minted via `connectProxy` so it reuses this client's connection\n * pool (HTTP/2 coalescing across sandboxes).\n */\n nativeClient?: import(\"./native-sandbox.js\").NativeSandboxClient;\n}\n\nexport interface CreateAndConnectOptions extends CreateSandboxOptions {\n poolId?: string;\n proxyUrl?: string;\n /** Total HTTP request timeout in seconds for sandbox startup. Default: client requestTimeout. */\n requestTimeout?: number;\n /** @deprecated Use requestTimeout. */\n startupTimeout?: number;\n}\n\n/**\n * Options for `Sandbox.getOrCreate`: everything `create` accepts (used only\n * when a new sandbox must be created; `name` comes from the first argument),\n * plus `resume`. `poolId` is excluded: a pool claim cannot carry a name, so\n * a claimed sandbox could never be found again by a later call.\n */\nexport interface GetOrCreateOptions\n extends Omit<CreateAndConnectOptions, \"name\" | \"poolId\"> {\n /** Resume a suspended sandbox before returning. Default: true. */\n resume?: boolean;\n}\n\n/**\n * What `Sandbox.getOrCreate` did to bind the name, exposed as\n * `sandbox.bindOutcome`:\n *\n * - `\"created\"`: nothing held the name; the call created a new sandbox.\n * - `\"attached\"`: a sandbox already held the name and needed no resume.\n * Includes a sandbox that was still starting (the call waited for it)\n * and a suspended sandbox when `resume: false`.\n * - `\"resumed\"`: the sandbox was suspended when the call found it and is\n * running now.\n */\nexport type GetOrCreateOutcome = \"created\" | \"attached\" | \"resumed\";\n\nexport interface SuspendResumeOptions {\n /** If false, fire-and-return without waiting for completion. Default: true. */\n wait?: boolean;\n /** Max seconds to wait when wait=true. Default: 300. */\n timeout?: number;\n /** Seconds between status polls when wait=true. Default: 1. */\n pollInterval?: number;\n}\n\nexport interface CheckpointOptions extends SuspendResumeOptions {\n checkpointType?: CheckpointType;\n /** Defaults to `\"local_ready\"`, which is enough to resume from a checkpoint. */\n waitUntil?: SnapshotWaitCondition;\n}\n\nexport interface ConnectOptions {\n sandboxId: string;\n proxyUrl?: string;\n routingHint?: string;\n}\n\n// --- JSON key conversion helpers ---\n\nconst CAMEL_TO_SNAKE_RE = /[A-Z]/g;\n\n/** Convert a camelCase string to snake_case. */\nexport function camelToSnake(str: string): string {\n return str.replace(CAMEL_TO_SNAKE_RE, (ch) => \"_\" + ch.toLowerCase());\n}\n\n/** Convert a snake_case string to camelCase. */\nexport function snakeToCamel(str: string): string {\n return str.replace(/_([a-z])/g, (_, ch) => ch.toUpperCase());\n}\n\n/** Recursively convert all object keys from camelCase to snake_case. */\nexport function toSnakeKeys(obj: unknown): unknown {\n if (Array.isArray(obj)) return obj.map(toSnakeKeys);\n if (obj !== null && typeof obj === \"object\" && !(obj instanceof Date)) {\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n result[camelToSnake(k)] = toSnakeKeys(v);\n }\n return result;\n }\n return obj;\n}\n\n/**\n * Parse a numeric timestamp into a Date.\n *\n * Handles seconds, milliseconds, and microseconds by checking magnitude.\n */\nexport function parseTimestamp(v: unknown): Date | undefined {\n if (v == null) return undefined;\n if (v instanceof Date) return v;\n if (typeof v === \"string\") {\n const parsed = Date.parse(v);\n return Number.isNaN(parsed) ? undefined : new Date(parsed);\n }\n const ts = Number(v);\n if (isNaN(ts)) return undefined;\n if (ts > 1e15) return new Date(ts / 1000); // microseconds → ms\n if (ts > 1e12) return new Date(ts); // already ms\n return new Date(ts * 1000); // seconds → ms\n}\n\n/**\n * Recursively convert all object keys from snake_case to camelCase,\n * with special handling for `id` → contextual name and timestamp parsing.\n */\nexport function fromSnakeKeys(obj: unknown, idField?: string): unknown {\n if (Array.isArray(obj))\n return obj.map((item) => fromSnakeKeys(item, idField));\n if (obj !== null && typeof obj === \"object\" && !(obj instanceof Date)) {\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n let key: string;\n if (k === \"id\" && idField) {\n key = idField;\n } else {\n key = snakeToCamel(k);\n }\n\n // Parse timestamp fields\n if (\n key.endsWith(\"At\") ||\n key === \"timestamp\" ||\n key === \"startedAt\" ||\n key === \"endedAt\"\n ) {\n result[key] = parseTimestamp(v);\n } else if (typeof v === \"object\" && v !== null && !Array.isArray(v)) {\n result[key] = fromSnakeKeys(v);\n } else if (Array.isArray(v)) {\n result[key] = v.map((item) => fromSnakeKeys(item));\n } else {\n // Normalize null → undefined so optional fields match TypeScript's ? convention.\n result[key] = v === null ? undefined : v;\n }\n }\n return result;\n }\n return obj;\n}\n","export interface SSEMessage {\n data: string;\n event?: string;\n id?: string;\n}\n\n/**\n * Parse a Server-Sent Events stream into raw SSE messages.\n */\nexport async function* parseSSEMessages(\n stream: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncIterable<SSEMessage> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n if (signal?.aborted) break;\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(/\\r?\\n\\r?\\n/);\n buffer = parts.pop() ?? \"\";\n\n for (const part of parts) {\n const lines = part.split(/\\r?\\n/);\n const dataLines: string[] = [];\n let event: string | undefined;\n let id: string | undefined;\n\n for (const line of lines) {\n if (!line || line.startsWith(\":\")) continue;\n\n const separator = line.indexOf(\":\");\n const field = separator === -1 ? line : line.slice(0, separator);\n let value = separator === -1 ? \"\" : line.slice(separator + 1);\n if (value.startsWith(\" \")) {\n value = value.slice(1);\n }\n\n if (field === \"data\") {\n dataLines.push(value);\n } else if (field === \"event\") {\n event = value;\n } else if (field === \"id\") {\n id = value;\n }\n }\n\n if (dataLines.length > 0 || event || id) {\n yield { data: dataLines.join(\"\\n\"), event, id };\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Parse a Server-Sent Events stream from a ReadableStream<Uint8Array>.\n *\n * Yields parsed JSON objects for each `data:` line. Handles reconnection\n * by simply yielding events as they arrive.\n */\nexport async function* parseSSEStream<T>(\n stream: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncIterable<T> {\n for await (const message of parseSSEMessages(stream, signal)) {\n if (!message.data) continue;\n try {\n yield JSON.parse(message.data) as T;\n } catch {\n // Skip malformed JSON\n }\n }\n}\n","import { nanoid } from \"nanoid\";\n\nimport * as defaults from \"./defaults.js\";\nimport { HttpClient } from \"./http.js\";\nimport { fromSnakeKeys } from \"./models.js\";\nimport { parseSSEStream } from \"./sse.js\";\nimport type {\n ApplicationBuildContext,\n ApplicationBuildResponse,\n ApplicationManifest,\n ApplicationSummary,\n BinaryPayload,\n BuildInfo,\n BuildLogEntry,\n CloudClientOptions,\n CreateApplicationBuildRequest,\n NewSecret,\n RequestInput,\n RequestMetadata,\n RequestOutput,\n SandboxTemplate,\n Secret,\n SecretsList,\n StartImageBuildRequest,\n UpsertSecretResponse,\n} from \"./cloud-models.js\";\n\nexport class CloudClient {\n private readonly http: HttpClient;\n private readonly organizationId?: string;\n private readonly projectId?: string;\n private readonly namespace: string;\n\n constructor(options?: CloudClientOptions) {\n this.organizationId = options?.organizationId;\n this.projectId = options?.projectId;\n this.namespace = options?.namespace ?? defaults.NAMESPACE;\n this.http = new HttpClient({\n baseUrl: options?.apiUrl ?? defaults.API_URL,\n apiKey: options?.apiKey ?? defaults.API_KEY,\n organizationId: this.organizationId,\n projectId: this.projectId,\n maxRetries: options?.maxRetries ?? defaults.MAX_RETRIES,\n retryBackoffMs: options?.retryBackoffMs ?? defaults.RETRY_BACKOFF_MS,\n });\n }\n\n static forCloud(options?: CloudClientOptions): CloudClient {\n return new CloudClient(options);\n }\n\n close(): void {\n this.http.close();\n }\n\n async upsertApplication(\n manifest: ApplicationManifest,\n codeZip: BinaryPayload,\n upgradeRunningRequests = false,\n ): Promise<void> {\n const applicationManifest = { ...manifest };\n let publicEndpointId = publicEndpointIdFromManifest(applicationManifest);\n if (\n applicationAllowsUnauthenticatedRequests(applicationManifest) &&\n publicEndpointId === undefined\n ) {\n const applicationName = applicationManifest.name;\n if (typeof applicationName === \"string\" && applicationName.length > 0) {\n publicEndpointId =\n await this.existingApplicationPublicEndpointId(applicationName);\n }\n publicEndpointId ??= generatePublicEndpointId();\n }\n if (publicEndpointId !== undefined) {\n applicationManifest.public_endpoint_id = publicEndpointId;\n delete applicationManifest.publicEndpointId;\n }\n\n const form = new FormData();\n form.append(\n \"code\",\n new Blob([toBlobPart(codeZip)], { type: \"application/zip\" }),\n \"code.zip\",\n );\n form.append(\"code_content_type\", \"application/zip\");\n form.append(\"application\", JSON.stringify(applicationManifest));\n form.append(\n \"upgrade_requests_to_latest_code\",\n String(upgradeRunningRequests),\n );\n\n await this.http.requestResponse(\"POST\", this.namespacePath(\"applications\"), {\n body: form,\n });\n }\n\n async deleteApplication(applicationName: string): Promise<void> {\n await this.http.requestResponse(\n \"DELETE\",\n this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),\n );\n }\n\n async deleteSandboxImage(imageName: string): Promise<void> {\n await this.http.requestResponse(\n \"DELETE\",\n this.namespacePath(`sandbox-images/${encodeURIComponent(imageName)}`),\n );\n }\n\n /**\n * Look up a registered sandbox image (template) by its registered name.\n *\n * Returns the template, or `null` when no image with that name exists.\n * API-key clients may omit organization/project IDs and use the\n * token-scoped Platform API route directly. Explicit scope remains\n * available for PAT callers.\n */\n async findSandboxImageByName(\n imageName: string,\n options?: { organizationId?: string; projectId?: string },\n ): Promise<SandboxTemplate | null> {\n const base = this.platformProjectPath(\n \"sandbox-templates\",\n options?.organizationId,\n options?.projectId,\n );\n const response = await this.http.requestResponse(\n \"GET\",\n `${base}/by-name/${encodeURIComponent(imageName)}`,\n { allowedErrorStatusCodes: new Set([404]) },\n );\n if (response.status === 404) {\n return null;\n }\n const raw = await parseJsonResponse<Record<string, unknown>>(response);\n return fromSnakeKeys(raw) as SandboxTemplate;\n }\n\n /**\n * List all registered sandbox images (templates), following pagination to\n * the end. API-key clients may omit organization/project IDs and use the\n * token-scoped Platform API route directly.\n */\n async listSandboxImages(\n options?: { organizationId?: string; projectId?: string },\n ): Promise<SandboxTemplate[]> {\n const base = this.platformProjectPath(\n \"sandbox-templates\",\n options?.organizationId,\n options?.projectId,\n );\n let path: string | null = `${base}?pageSize=100`;\n const templates: SandboxTemplate[] = [];\n while (path !== null) {\n const page: SandboxTemplatesPage = await this.http.requestJson<SandboxTemplatesPage>(\n \"GET\",\n path,\n );\n for (const item of page.items ?? []) {\n templates.push(fromSnakeKeys(item) as SandboxTemplate);\n }\n const next = page.pagination?.next;\n path = next ? nextRequestPath(next) : null;\n }\n return templates;\n }\n\n async applications(): Promise<ApplicationSummary[]> {\n const raw = await this.http.requestJson<{ applications: Record<string, unknown>[] }>(\n \"GET\",\n this.namespacePath(\"applications\"),\n );\n return (raw.applications ?? []).map(\n (application) => fromSnakeKeys(application) as ApplicationSummary,\n );\n }\n\n async applicationManifest(applicationName: string): Promise<ApplicationManifest> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"GET\",\n this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),\n );\n return fromSnakeKeys(raw) as ApplicationManifest;\n }\n\n async runRequest(\n applicationName: string,\n inputs: RequestInput[] = [],\n ): Promise<string> {\n const path = this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}`,\n );\n\n const response =\n inputs.length === 0\n ? await this.http.requestResponse(\"POST\", path, {\n body: new Uint8Array(),\n headers: { Accept: \"application/json\" },\n })\n : inputs.length === 1 && inputs[0].name === \"0\"\n ? await this.http.requestResponse(\"POST\", path, {\n body: toRequestBody(inputs[0].data),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": inputs[0].contentType,\n },\n })\n : await this.runMultipartRequest(path, inputs);\n\n const body = await parseJsonResponse<{ request_id?: string }>(response);\n const requestId = body?.request_id;\n if (!requestId) {\n throw new Error(\"missing request_id in run request response body\");\n }\n return requestId;\n }\n\n async waitOnRequestCompletion(\n applicationName: string,\n requestId: string,\n ): Promise<void> {\n const stream = await this.http.requestStream(\n \"GET\",\n this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/progress`,\n ),\n );\n\n for await (const event of parseSSEStream<Record<string, unknown>>(stream)) {\n if (Object.prototype.hasOwnProperty.call(event, \"RequestFinished\")) {\n return;\n }\n }\n\n throw new Error(\"progress stream ended before request completion\");\n }\n\n async requestMetadata(\n applicationName: string,\n requestId: string,\n ): Promise<RequestMetadata> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"GET\",\n this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}`,\n ),\n );\n return fromSnakeKeys(raw) as RequestMetadata;\n }\n\n async requestOutput(\n applicationName: string,\n requestId: string,\n ): Promise<RequestOutput> {\n const response = await this.http.requestResponse(\n \"GET\",\n this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/output`,\n ),\n );\n\n const serializedValue = new Uint8Array(await response.arrayBuffer());\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n return {\n serializedValue,\n contentType,\n };\n }\n\n async listSecrets(options?: {\n organizationId?: string;\n projectId?: string;\n pageSize?: number;\n }): Promise<SecretsList> {\n const base = this.secretCollectionPath(\n options?.organizationId,\n options?.projectId,\n );\n const raw = await this.http.requestJson<SecretMetadata[]>(\"GET\", base);\n const pageSize = Math.max(0, options?.pageSize ?? 100);\n return Object.assign(\n {\n items: raw.slice(0, pageSize).map(secretFromMetadata),\n pagination: { total: raw.length },\n },\n { traceId: raw.traceId },\n );\n }\n\n async getSecret(\n secretId: string,\n options?: { organizationId?: string; projectId?: string },\n ): Promise<Secret> {\n const base = this.secretCollectionPath(\n options?.organizationId,\n options?.projectId,\n );\n const raw = await this.http.requestJson<SecretMetadata>(\n \"GET\",\n `${base}/${encodeURIComponent(secretId)}`,\n );\n return Object.assign(secretFromMetadata(raw), { traceId: raw.traceId });\n }\n\n async upsertSecrets(\n secrets: NewSecret | NewSecret[],\n options?: { organizationId?: string; projectId?: string },\n ): Promise<UpsertSecretResponse> {\n const base = this.secretCollectionPath(\n options?.organizationId,\n options?.projectId,\n );\n if (Array.isArray(secrets)) {\n const results: Secret[] = [];\n for (const secret of secrets) {\n results.push(await this.upsertSecret(base, secret));\n }\n return results;\n }\n return this.upsertSecret(base, secrets);\n }\n\n async deleteSecret(\n secretId: string,\n options?: { organizationId?: string; projectId?: string },\n ): Promise<void> {\n const base = this.secretCollectionPath(\n options?.organizationId,\n options?.projectId,\n );\n await this.http.requestResponse(\n \"DELETE\",\n `${base}/${encodeURIComponent(secretId)}`,\n );\n }\n\n private async upsertSecret(base: string, secret: NewSecret): Promise<Secret> {\n let response = await this.http.requestResponse(\"POST\", base, {\n json: secret,\n headers: { \"Idempotency-Key\": nanoid() },\n allowedErrorStatusCodes: new Set([409]),\n });\n if (response.status === 409) {\n const prefix = base.slice(0, -\"/secrets\".length);\n const existing = await this.http.requestJson<{ id: string }>(\n \"GET\",\n `${prefix}/secret-names/${encodeURIComponent(secret.name)}`,\n );\n response = await this.http.requestResponse(\n \"POST\",\n `${base}/${encodeURIComponent(existing.id)}/versions`,\n {\n json: { value: secret.value },\n headers: { \"Idempotency-Key\": nanoid() },\n },\n );\n }\n const metadata = await parseJsonResponse<SecretMetadata>(response);\n return Object.assign(secretFromMetadata(metadata), {\n traceId: response.traceId,\n });\n }\n\n async startImageBuild(\n buildServicePath: string,\n request: StartImageBuildRequest,\n ): Promise<BuildInfo> {\n const form = new FormData();\n form.append(\"graph_name\", request.applicationName);\n form.append(\"graph_version\", request.applicationVersion);\n form.append(\"graph_function_name\", request.functionName);\n form.append(\"image_name\", request.imageName);\n form.append(\"image_id\", request.imageId);\n form.append(\n \"context\",\n new Blob([toBlobPart(request.buildContext)]),\n \"context.tar.gz\",\n );\n\n const response = await this.http.requestResponse(\n \"PUT\",\n `${trimTrailingSlashes(buildServicePath)}/builds`,\n { body: form },\n );\n const raw = await parseJsonResponse<Record<string, unknown>>(response);\n return fromSnakeKeys(raw) as BuildInfo;\n }\n\n async createApplicationBuild(\n buildServicePath: string,\n request: CreateApplicationBuildRequest,\n imageContexts: ApplicationBuildContext[],\n ): Promise<ApplicationBuildResponse> {\n const form = createApplicationBuildForm(request, imageContexts);\n const response = await this.http.requestResponse(\n \"POST\",\n trimTrailingSlashes(buildServicePath),\n { body: form },\n );\n const raw = await parseJsonResponse<Record<string, unknown>>(response);\n return fromSnakeKeys(raw) as ApplicationBuildResponse;\n }\n\n async applicationBuildInfo(\n buildServicePath: string,\n applicationBuildId: string,\n ): Promise<ApplicationBuildResponse> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"GET\",\n `${trimTrailingSlashes(buildServicePath)}/${encodeURIComponent(applicationBuildId)}`,\n );\n return fromSnakeKeys(raw) as ApplicationBuildResponse;\n }\n\n async cancelApplicationBuild(\n buildServicePath: string,\n applicationBuildId: string,\n ): Promise<ApplicationBuildResponse> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"POST\",\n `${trimTrailingSlashes(buildServicePath)}/${encodeURIComponent(applicationBuildId)}/cancel`,\n );\n return fromSnakeKeys(raw) as ApplicationBuildResponse;\n }\n\n async buildInfo(\n buildServicePath: string,\n buildId: string,\n ): Promise<BuildInfo> {\n const raw = await this.http.requestJson<Record<string, unknown>>(\n \"GET\",\n `${trimTrailingSlashes(buildServicePath)}/builds/${encodeURIComponent(buildId)}`,\n );\n return fromSnakeKeys(raw) as BuildInfo;\n }\n\n async cancelBuild(buildServicePath: string, buildId: string): Promise<void> {\n await this.http.requestResponse(\n \"POST\",\n `${trimTrailingSlashes(buildServicePath)}/builds/${encodeURIComponent(buildId)}/cancel`,\n );\n }\n\n async *streamBuildLogs(\n buildServicePath: string,\n buildId: string,\n signal?: AbortSignal,\n ): AsyncIterable<BuildLogEntry> {\n const stream = await this.http.requestStream(\n \"GET\",\n `${trimTrailingSlashes(buildServicePath)}/builds/${encodeURIComponent(buildId)}/logs`,\n { signal },\n );\n for await (const event of parseSSEStream<Record<string, unknown>>(stream, signal)) {\n yield fromSnakeKeys(event) as BuildLogEntry;\n }\n }\n\n private async runMultipartRequest(\n path: string,\n inputs: RequestInput[],\n ): Promise<Response> {\n const form = new FormData();\n for (const input of inputs) {\n form.append(\n input.name,\n new Blob([toBlobPart(input.data)], { type: input.contentType }),\n input.name,\n );\n }\n return this.http.requestResponse(\"POST\", path, {\n body: form,\n headers: { Accept: \"application/json\" },\n });\n }\n\n private namespacePath(subpath: string): string {\n return `/v1/namespaces/${encodeURIComponent(this.namespace)}/${subpath.replace(/^\\/+/, \"\")}`;\n }\n\n private async existingApplicationPublicEndpointId(\n applicationName: string,\n ): Promise<string | undefined> {\n const response = await this.http.requestResponse(\n \"GET\",\n this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),\n { allowedErrorStatusCodes: new Set([404]) },\n );\n if (response.status === 404) {\n return undefined;\n }\n\n const application =\n await parseJsonResponse<Record<string, unknown>>(response);\n return publicEndpointIdFromManifest(application);\n }\n\n private platformProjectPath(\n resource: \"sandbox-templates\",\n organizationId?: string,\n projectId?: string,\n ): string {\n const resolvedOrganizationId = organizationId ?? this.organizationId;\n const resolvedProjectId = projectId ?? this.projectId;\n if (!resolvedOrganizationId && !resolvedProjectId) {\n return `/platform/v1/${resource}`;\n }\n if (!resolvedOrganizationId || !resolvedProjectId) {\n throw new Error(\n \"organizationId and projectId must be provided together\",\n );\n }\n return `/platform/v1/organizations/${encodeURIComponent(resolvedOrganizationId)}/projects/${encodeURIComponent(resolvedProjectId)}/${resource}`;\n }\n\n private secretCollectionPath(\n organizationId?: string,\n projectId?: string,\n ): string {\n const resolvedOrganizationId = organizationId ?? this.organizationId;\n const resolvedProjectId = projectId ?? this.projectId;\n if (!resolvedOrganizationId && !resolvedProjectId) {\n return this.namespacePath(\"secrets\");\n }\n if (!resolvedOrganizationId || !resolvedProjectId) {\n throw new Error(\"organizationId and projectId must be provided together\");\n }\n return this.namespacePath(\"secrets\");\n }\n}\n\ntype SecretMetadata = {\n id: string;\n name: string;\n created_at_ms: number;\n};\n\nfunction secretFromMetadata(metadata: SecretMetadata): Secret {\n return {\n id: metadata.id,\n name: metadata.name,\n createdAt: new Date(metadata.created_at_ms),\n };\n}\n\nconst UNAUTHENTICATED_REQUESTS = \"unauthenticated_requests\";\n\nfunction applicationAllowsUnauthenticatedRequests(\n manifest: ApplicationManifest,\n): boolean {\n return (\n Array.isArray(manifest.allow) &&\n manifest.allow.includes(UNAUTHENTICATED_REQUESTS)\n );\n}\n\nfunction publicEndpointIdFromManifest(\n manifest: ApplicationManifest,\n): string | undefined {\n for (const key of [\"public_endpoint_id\", \"publicEndpointId\"]) {\n const value = manifest[key];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction generatePublicEndpointId(): string {\n return `endpoint_${nanoid()}`;\n}\n\nfunction createApplicationBuildForm(\n request: CreateApplicationBuildRequest,\n imageContexts: ApplicationBuildContext[],\n): FormData {\n const contextsByPartName = new Map<string, ApplicationBuildContext>();\n for (const context of imageContexts) {\n if (contextsByPartName.has(context.contextTarPartName)) {\n throw new Error(\n `duplicate image context part name '${context.contextTarPartName}'`,\n );\n }\n contextsByPartName.set(context.contextTarPartName, context);\n }\n\n const form = new FormData();\n form.append(\n \"app_version\",\n new Blob([JSON.stringify(request)], { type: \"application/json\" }),\n \"app_version\",\n );\n\n for (const image of request.images) {\n const context = contextsByPartName.get(image.contextTarPartName);\n if (!context) {\n throw new Error(\n `missing image context for part '${image.contextTarPartName}'`,\n );\n }\n form.append(\n image.contextTarPartName,\n new Blob([toBlobPart(context.contextTarGz)]),\n `${image.contextTarPartName}.tar.gz`,\n );\n }\n\n for (const context of imageContexts) {\n if (!request.images.some((image) => image.contextTarPartName === context.contextTarPartName)) {\n throw new Error(\n `unexpected image context for part '${context.contextTarPartName}'`,\n );\n }\n }\n\n return form;\n}\n\nfunction trimTrailingSlashes(value: string): string {\n return value.endsWith(\"/\") ? value.slice(0, -1) : value;\n}\n\n/** One page of the paginated sandbox-templates list response. */\ninterface SandboxTemplatesPage {\n items?: Record<string, unknown>[];\n pagination?: { next?: string };\n}\n\n/**\n * Reduce a `pagination.next` link to a base-URL-relative request path. The\n * server may return either an absolute URL or an absolute path; the HTTP\n * client always prepends its base URL, so absolute URLs must be reduced to\n * their path+query first.\n */\nfunction nextRequestPath(next: string): string {\n const schemeIndex = next.indexOf(\"://\");\n if (schemeIndex !== -1) {\n const afterScheme = next.slice(schemeIndex + 3);\n const slashIndex = afterScheme.indexOf(\"/\");\n return slashIndex === -1 ? \"/\" : afterScheme.slice(slashIndex);\n }\n return next.startsWith(\"/\") ? next : `/${next}`;\n}\n\nfunction toBlobPart(data: BinaryPayload): string | Blob | ArrayBuffer {\n if (typeof data === \"string\" || data instanceof Blob) {\n return data;\n }\n if (data instanceof Uint8Array) {\n return Uint8Array.from(data).buffer;\n }\n return data;\n}\n\nfunction toRequestBody(data: BinaryPayload): string | Blob | ArrayBuffer {\n return toBlobPart(data);\n}\n\nasync function parseJsonResponse<T>(response: Response): Promise<T> {\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n}\n","import { randomUUID } from \"node:crypto\";\n\n// Erased at runtime — safe despite the module cycle with sandbox-image.ts,\n// which imports Image from here.\nimport type { CreateSandboxImageOptions } from \"./sandbox-image.js\";\n\nconst DEFAULT_IMAGE_NAME = \"default\";\n\nexport const ImageBuildOperationType = {\n ADD: \"ADD\",\n COPY: \"COPY\",\n ENV: \"ENV\",\n RUN: \"RUN\",\n WORKDIR: \"WORKDIR\",\n} as const;\n\nexport type ImageBuildOperationType =\n (typeof ImageBuildOperationType)[keyof typeof ImageBuildOperationType];\n\nexport interface ImageBuildOperation {\n type: ImageBuildOperationType;\n args: string[];\n options: Record<string, string>;\n}\n\nexport interface ImageOptions {\n name?: string;\n tag?: string;\n baseImage?: string | null;\n}\n\nfunction cloneOperation(op: ImageBuildOperation): ImageBuildOperation {\n return {\n type: op.type,\n args: [...op.args],\n options: { ...op.options },\n };\n}\n\nexport class Image {\n readonly _id: string;\n readonly _name: string;\n readonly _tag: string;\n readonly _baseImage: string | null;\n readonly _buildOperations: ImageBuildOperation[];\n\n constructor();\n constructor(name: string, tag?: string, baseImage?: string | null);\n constructor(options: ImageOptions);\n constructor(\n nameOrOptions: string | ImageOptions = {},\n tag = \"latest\",\n baseImage: string | null = null,\n ) {\n this._id = randomUUID();\n this._buildOperations = [];\n\n if (typeof nameOrOptions === \"string\") {\n this._name = nameOrOptions;\n this._tag = tag;\n this._baseImage = baseImage;\n return;\n }\n\n this._name = nameOrOptions.name ?? DEFAULT_IMAGE_NAME;\n this._tag = nameOrOptions.tag ?? \"latest\";\n this._baseImage = nameOrOptions.baseImage ?? null;\n }\n\n get name(): string {\n return this._name;\n }\n\n get tag(): string {\n return this._tag;\n }\n\n get baseImage(): string | null {\n return this._baseImage;\n }\n\n get buildOperations(): ImageBuildOperation[] {\n return this._buildOperations.map(cloneOperation);\n }\n\n add(\n src: string,\n dest: string,\n options: Record<string, string> | undefined = undefined,\n ): this {\n return this._addOperation({\n type: ImageBuildOperationType.ADD,\n args: [src, dest],\n options: options == null ? {} : { ...options },\n });\n }\n\n copy(\n src: string,\n dest: string,\n options: Record<string, string> | undefined = undefined,\n ): this {\n return this._addOperation({\n type: ImageBuildOperationType.COPY,\n args: [src, dest],\n options: options == null ? {} : { ...options },\n });\n }\n\n env(key: string, value: string): this {\n return this._addOperation({\n type: ImageBuildOperationType.ENV,\n args: [key, value],\n options: {},\n });\n }\n\n run(\n commands: string | string[],\n options: Record<string, string> | undefined = undefined,\n ): this {\n return this._addOperation({\n type: ImageBuildOperationType.RUN,\n args: Array.isArray(commands) ? [...commands] : [commands],\n options: options == null ? {} : { ...options },\n });\n }\n\n workdir(directory: string): this {\n return this._addOperation({\n type: ImageBuildOperationType.WORKDIR,\n args: [directory],\n options: {},\n });\n }\n\n /**\n * Build this image as a sandbox template and register it.\n *\n * Materializes the image in a build sandbox, snapshots the filesystem,\n * and registers the snapshot as a named sandbox template.\n */\n async build(\n options: CreateSandboxImageOptions = {},\n ): Promise<Record<string, unknown>> {\n const { createSandboxImage } = await import(\"./sandbox-image.js\");\n return createSandboxImage(this, options);\n }\n\n private _addOperation(op: ImageBuildOperation): this {\n this._buildOperations.push(op);\n return this;\n }\n}\n\nfunction renderOptions(options: Record<string, string>): string {\n const entries = Object.entries(options);\n if (entries.length === 0) {\n return \"\";\n }\n return ` ${entries.map(([key, value]) => `--${key}=${value}`).join(\" \")}`;\n}\n\nfunction renderBuildOp(op: ImageBuildOperation): string {\n const options = renderOptions(op.options);\n if (op.type === ImageBuildOperationType.ENV) {\n return `ENV${options} ${op.args[0]}=${JSON.stringify(op.args[1])}`;\n }\n return `${op.type}${options} ${op.args.join(\" \")}`;\n}\n\nexport function dockerfileContent(image: Image): string {\n const lines = image.baseImage == null ? [] : [`FROM ${image.baseImage}`];\n lines.push(...image.buildOperations.map((op) => renderBuildOp(op)));\n return lines.join(\"\\n\");\n}\n","// Read the ELF interpreter, rather than generating a process-wide diagnostic\n// report. Both supported Linux architectures use little-endian ELF64. Reads\n// are bounded to the header, program headers, and interpreter pathname.\nfunction detectLinuxLibc(fs, executable = process.execPath) {\n const override = process.env.TENSORLAKE_NODE_LIBC;\n if (override != null) {\n if (override === \"gnu\" || override === \"musl\") return override;\n throw new Error(\"TENSORLAKE_NODE_LIBC must be 'gnu' or 'musl'.\");\n }\n\n let fd;\n try {\n fd = fs.openSync(executable, \"r\");\n function read(size, offset) {\n if (!Number.isSafeInteger(offset) || offset < 0) {\n throw new Error(\"Invalid ELF offset\");\n }\n const buffer = Buffer.alloc(size);\n let count = 0;\n while (count < size) {\n const bytes = fs.readSync(fd, buffer, count, size - count, offset + count);\n if (bytes === 0) throw new Error(\"Truncated ELF executable\");\n count += bytes;\n }\n return buffer;\n }\n\n const header = read(64, 0);\n if (header.readUInt32BE(0) !== 0x7f454c46 || header[4] !== 2 || header[5] !== 1) {\n throw new Error(\"Expected a little-endian ELF64 executable\");\n }\n const entrySize = header.readUInt16LE(54);\n const count = header.readUInt16LE(56);\n if (entrySize !== 56 || count === 0 || count > 128) {\n throw new Error(\"Unsupported ELF program headers\");\n }\n const entries = read(entrySize * count, Number(header.readBigUInt64LE(32)));\n for (let i = 0; i < count; i++) {\n const offset = i * entrySize;\n if (entries.readUInt32LE(offset) !== 3) continue; // PT_INTERP\n const size = Number(entries.readBigUInt64LE(offset + 32));\n if (size < 2 || size > 4096) throw new Error(\"Invalid ELF interpreter size\");\n const interpreter = read(size, Number(entries.readBigUInt64LE(offset + 8)));\n if (interpreter[size - 1] !== 0) throw new Error(\"Unterminated ELF interpreter\");\n const name = interpreter.subarray(0, -1).toString(\"utf8\").split(\"/\").at(-1);\n if (name.startsWith(\"ld-musl-\")) return \"musl\";\n if (name.startsWith(\"ld-linux-\")) return \"gnu\";\n throw new Error(\"Unrecognized ELF interpreter\");\n }\n throw new Error(\"No ELF interpreter (statically linked executable)\");\n } catch (cause) {\n throw new Error(\n \"Unable to detect Linux libc from the Node executable. Set TENSORLAKE_NODE_LIBC to 'gnu' or 'musl' for a nonstandard runtime.\",\n { cause },\n );\n } finally {\n if (fd != null) fs.closeSync(fd);\n }\n}\n\nmodule.exports = { detectLinuxLibc };\n","import { detectLinuxLibc } from \"../lib/libc.cjs\";\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\ninterface RuntimeReport {\n header?: {\n glibcVersionRuntime?: string;\n };\n}\n\ninterface TargetOptions {\n libc?: \"gnu\" | \"musl\";\n report?: RuntimeReport;\n}\n\ninterface NativeBindingPathOptions extends TargetOptions {\n packageRoot?: string;\n platform?: NodeJS.Platform;\n arch?: string;\n}\n\nconst NATIVE_PACKAGES: Readonly<Record<string, string>> = {\n \"darwin-arm64\": \"tensorlake-native-darwin-arm64\",\n \"linux-arm64\": \"tensorlake-native-linux-arm64-gnu\",\n \"linux-arm64-musl\": \"tensorlake-native-linux-arm64-musl\",\n \"linux-x64\": \"tensorlake-native-linux-x64-gnu\",\n \"linux-x64-musl\": \"tensorlake-native-linux-x64-musl\",\n \"win32-x64\": \"tensorlake-native-win32-x64\",\n};\n\nfunction packageRoot(): string {\n const parent = fileURLToPath(new URL(\"../\", import.meta.url));\n if (fs.existsSync(path.join(parent, \"package.json\"))) return parent;\n const grandparent = fileURLToPath(new URL(\"../../\", import.meta.url));\n if (fs.existsSync(path.join(grandparent, \"package.json\"))) return grandparent;\n return parent;\n}\n\nlet cachedLinuxLibc: \"gnu\" | \"musl\" | undefined;\n\nfunction linuxLibcFamily(options: TargetOptions): \"gnu\" | \"musl\" {\n if (options.libc != null) return options.libc;\n if (options.report != null) {\n return options.report.header?.glibcVersionRuntime ? \"gnu\" : \"musl\";\n }\n if (cachedLinuxLibc != null) return cachedLinuxLibc;\n\n cachedLinuxLibc = detectLinuxLibc(fs);\n return cachedLinuxLibc;\n}\n\nexport function nativeTargetId(\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n options: TargetOptions = {},\n): string {\n const target = `${platform}-${arch}`;\n if (platform !== \"linux\") return target;\n if (options.libc == null && options.report == null && platform !== process.platform) {\n return target;\n }\n return linuxLibcFamily(options) === \"musl\" ? `${target}-musl` : target;\n}\n\nexport function nativeBindingPath(options: NativeBindingPathOptions = {}): string {\n const platform = options.platform ?? process.platform;\n const arch = options.arch ?? process.arch;\n return path.join(\n options.packageRoot ?? packageRoot(),\n \"dist\",\n \"native\",\n nativeTargetId(platform, arch, options),\n \"tensorlake-node.node\",\n );\n}\n\nexport function nativePackageName(\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n options: TargetOptions = {},\n): string | undefined {\n return NATIVE_PACKAGES[nativeTargetId(platform, arch, options)];\n}\n\nexport function loadNative<T>(): T {\n const target = nativeTargetId();\n const bindingPath = nativeBindingPath();\n const require = createRequire(import.meta.url);\n\n // Local source builds stage the addon here. Published packages intentionally\n // omit this directory and resolve the platform-specific optional dependency.\n if (fs.existsSync(bindingPath)) return require(bindingPath) as T;\n\n const packageName = nativePackageName();\n if (!packageName) {\n throw new Error(\n `Tensorlake does not provide a native binding for ${target}.`,\n );\n }\n\n let packageEntry: string;\n try {\n packageEntry = require.resolve(packageName);\n } catch (cause) {\n throw new Error(\n `Missing native binding package ${packageName} for ${target}. Reinstall tensorlake without omitting optional dependencies, and install dependencies on the machine where they will run.`,\n { cause },\n );\n }\n return require(packageEntry) as T;\n}\n","import path from \"node:path\";\nimport os from \"node:os\";\nimport { existsSync, mkdtempSync, rmSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\nimport { CloudClient } from \"./cloud-client.js\";\nimport type { SandboxTemplate } from \"./cloud-models.js\";\nimport { Image, ImageBuildOperationType, dockerfileContent } from \"./image.js\";\nimport type { ImageBuildOperation } from \"./image.js\";\nimport { loadNative } from \"./native-binding.js\";\n\n/**\n * Sandbox-image build engine.\n *\n * Renders the source to a Dockerfile (for `Image` inputs) and hands the\n * Dockerfile path/text + context to the Rust core via the platform-specific native binding,\n * which parses, validates, materializes, and registers the image. The Rust\n * core owns parsing and the warnings for instructions that run during the\n * build but have no effect when a sandbox runs from the image\n * (`ONBUILD`/`SHELL`/`EXPOSE`/`HEALTHCHECK`/`LABEL`/`STOPSIGNAL`/`VOLUME`).\n */\n\nexport interface CreateSandboxImageOptions {\n registeredName?: string;\n cpus?: number;\n memoryMb?: number;\n diskMb?: number;\n builderDiskMb?: number;\n isPublic?: boolean;\n /**\n * Build context directory for an `Image` source, used exactly like\n * `docker build <contextDir>`: it is uploaded as-is and COPY/ADD sources\n * resolve relative to it. Required when the image has COPY/ADD ops that read\n * host files — building without it then throws. When the image has no such\n * ops it may be omitted, and an empty context (just the generated Dockerfile)\n * is uploaded so cwd is not archived. Ignored when the source is a Dockerfile\n * path (the Dockerfile's parent directory is used instead).\n */\n contextDir?: string;\n /**\n * Use Docker/BuildKit max compatibility mode (build is slower and uses more\n * memory and disk space on builder sandbox).\n */\n dockerCompat?: boolean;\n /**\n * Print build progress to stderr. Ignored when an explicit `emit` is\n * passed via `deps`. Defaults to false — `createSandboxImage` is silent\n * by default when invoked programmatically (e.g. `Image.build()`).\n */\n verbose?: boolean;\n}\n\nexport interface ImportSandboxImageOptions {\n /**\n * Name to register the image under. Defaults to the image reference's last\n * path segment with any tag/digest stripped (e.g. `pytorch/pytorch:2.4.1`\n * -> `pytorch`).\n */\n registeredName?: string;\n cpus?: number;\n memoryMb?: number;\n diskMb?: number;\n builderDiskMb?: number;\n isPublic?: boolean;\n /**\n * Use Docker/BuildKit max compatibility mode (import is slower and uses more\n * memory and disk space on builder sandbox).\n */\n dockerCompat?: boolean;\n /**\n * Print build progress to stderr. Ignored when an explicit `emit` is\n * passed via `deps`. Defaults to false.\n */\n verbose?: boolean;\n}\n\nexport type SandboxImageSource = string | Image;\n\nexport interface CreateSandboxImageDeps {\n emit?: (event: Record<string, unknown>) => void;\n /** @internal Standalone CLI entry points allow PAT auth; SDK callers do not. */\n _allowPat?: boolean;\n}\n\n// --- Native binding loader -------------------------------------------------\n\n/** Auth/context + resource fields shared by the build and import bindings. */\ninterface NativeBindingCommonOptions {\n apiUrl: string;\n bearerToken: string;\n registeredName?: string | undefined | null;\n diskMb?: number | undefined | null;\n builderDiskMb?: number | undefined | null;\n cpus?: number | undefined | null;\n memoryMb?: number | undefined | null;\n isPublic?: boolean | undefined | null;\n organizationId?: string | undefined | null;\n projectId?: string | undefined | null;\n namespace?: string | undefined | null;\n useScopeHeaders?: boolean | undefined | null;\n userAgent?: string | undefined | null;\n dockerCompat?: boolean | undefined | null;\n}\n\ninterface NativeBindingOptions extends NativeBindingCommonOptions {\n dockerfilePath: string;\n dockerfileText?: string | undefined | null;\n contextDir?: string | undefined | null;\n}\n\ninterface NativeBindingImportOptions extends NativeBindingCommonOptions {\n imageReference: string;\n}\n\ninterface NativeBindingEvent {\n eventType: string;\n stream?: string | undefined | null;\n message: string;\n}\n\ninterface NativeBinding {\n buildSandboxImage(\n options: NativeBindingOptions,\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n ): Promise<string>;\n importSandboxImage(\n options: NativeBindingImportOptions,\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n ): Promise<string>;\n}\n\nlet cachedNativeBinding: NativeBinding | undefined;\nlet cachedNativeBindingError: Error | undefined;\n\nfunction loadNativeBinding(): NativeBinding {\n if (cachedNativeBinding) return cachedNativeBinding;\n if (cachedNativeBindingError) throw cachedNativeBindingError;\n try {\n cachedNativeBinding = loadNative<NativeBinding>();\n return cachedNativeBinding;\n } catch (error) {\n cachedNativeBindingError =\n error instanceof Error ? error : new Error(String(error));\n throw cachedNativeBindingError;\n }\n}\n\n/** Test seam: replace the native binding with a stub. */\nexport function __setNativeBindingForTest(binding: NativeBinding | undefined): void {\n cachedNativeBinding = binding;\n cachedNativeBindingError = undefined;\n}\n\n// --- Build context ---------------------------------------------------------\n\nexport interface BuildContext {\n apiUrl: string;\n apiKey?: string;\n personalAccessToken?: string;\n namespace: string;\n organizationId?: string;\n projectId?: string;\n debug: boolean;\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n return value && value.length > 0 ? value : undefined;\n}\n\nexport function buildContextFromEnv(): BuildContext {\n const debugRaw = (process.env.TENSORLAKE_DEBUG ?? \"\").toLowerCase();\n const debug = [\"1\", \"true\", \"yes\", \"on\"].includes(debugRaw);\n return {\n apiUrl: nonEmpty(process.env.TENSORLAKE_API_URL) ?? \"https://api.tensorlake.ai\",\n apiKey: nonEmpty(process.env.TENSORLAKE_API_KEY),\n personalAccessToken: nonEmpty(process.env.TENSORLAKE_PAT),\n namespace: nonEmpty(process.env.INDEXIFY_NAMESPACE) ?? \"default\",\n organizationId: nonEmpty(process.env.TENSORLAKE_ORGANIZATION_ID),\n projectId: nonEmpty(process.env.TENSORLAKE_PROJECT_ID),\n debug,\n };\n}\n\n// --- Default-name helper ---------------------------------------------------\n\nconst DEFAULT_IMAGE_NAME = \"default\";\n\nfunction defaultRegisteredName(dockerfilePath: string): string {\n const parsed = path.parse(dockerfilePath);\n if (parsed.name.toLowerCase() === \"dockerfile\") {\n const parentName = path.basename(path.dirname(dockerfilePath)).trim();\n return parentName || \"sandbox-image\";\n }\n return parsed.name || \"sandbox-image\";\n}\n\n/**\n * Mirror the Rust core's default name derivation for image imports: the last\n * path segment of the reference with any tag/digest stripped\n * (e.g. `pytorch/pytorch:2.4.1` -> `pytorch`, `ghcr.io/org/app@sha256:...`\n * -> `app`).\n */\nfunction defaultRegisteredNameFromImage(imageReference: string): string {\n const withoutDigest = imageReference.split(\"@\", 1)[0] ?? imageReference;\n const lastSegment = withoutDigest.split(\"/\").pop() ?? withoutDigest;\n const colonIndex = lastSegment.lastIndexOf(\":\");\n const name =\n colonIndex > 0 && colonIndex < lastSegment.length - 1\n ? lastSegment.slice(0, colonIndex)\n : lastSegment;\n return name || \"imported-image\";\n}\n\n// --- Emit helpers ----------------------------------------------------------\n\nfunction noopEmit(_event: Record<string, unknown>): void {}\n\nfunction stderrEmit(event: Record<string, unknown>): void {\n const message = typeof event.message === \"string\" ? event.message : \"\";\n const type = typeof event.type === \"string\" ? event.type : \"\";\n if (type === \"build_log\") {\n const stream = typeof event.stream === \"string\" ? event.stream : \"stdout\";\n process.stderr.write(`[${stream}] ${message}\\n`);\n } else if (message) {\n process.stderr.write(`[${type}] ${message}\\n`);\n }\n}\n\nfunction ndjsonStdoutEmit(event: Record<string, unknown>): void {\n process.stdout.write(`${JSON.stringify(event)}\\n`);\n}\n\nfunction eventToEmitDict(event: NativeBindingEvent): Record<string, unknown> {\n const out: Record<string, unknown> = {\n type: event.eventType,\n message: event.message,\n };\n if (event.stream != null) out.stream = event.stream;\n return out;\n}\n\n/**\n * True when a `RUN` op bind-mounts the build context (reads host files).\n * A BuildKit `RUN --mount=type=bind` reads from the build context unless it\n * mounts `from=<stage/image>`. `bind` is the default mount type, so a mount\n * with no explicit `type` counts too. Other mount types\n * (`cache`/`tmpfs`/`secret`/`ssh`) don't read the build context.\n */\nfunction runOpMountsContext(op: ImageBuildOperation): boolean {\n if (op.type !== ImageBuildOperationType.RUN) {\n return false;\n }\n const mount = op.options.mount;\n if (mount == null || mount === \"\") {\n return false;\n }\n const fields: Record<string, string> = {};\n for (const token of mount.split(\",\")) {\n const eq = token.indexOf(\"=\");\n const key = (eq === -1 ? token : token.slice(0, eq)).trim();\n const value = eq === -1 ? \"\" : token.slice(eq + 1).trim();\n fields[key] = value;\n }\n if ((fields.type ?? \"bind\") !== \"bind\") {\n return false;\n }\n return !(\"from\" in fields);\n}\n\n/**\n * True when a build op reads files from the host build context.\n * `COPY`/`ADD` with host sources need a context; a `RUN` with a\n * `--mount=type=bind` (the default type) reads it too. `COPY --from=<stage>`,\n * remote `ADD <url>`, `from=` bind mounts, and non-bind mounts don't.\n */\nfunction opReferencesHostFiles(op: ImageBuildOperation): boolean {\n if (op.type === ImageBuildOperationType.RUN) {\n return runOpMountsContext(op);\n }\n if (\n op.type !== ImageBuildOperationType.COPY &&\n op.type !== ImageBuildOperationType.ADD\n ) {\n return false;\n }\n if (op.options.from != null) {\n return false;\n }\n if (\n op.type === ImageBuildOperationType.ADD &&\n (op.args[0].startsWith(\"http://\") || op.args[0].startsWith(\"https://\"))\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * True if the image has ops that read files from the host (COPY/ADD host\n * sources, or a RUN bind mount). Such builds need a build context to resolve\n * those sources, so the caller must pass `contextDir` (mirroring\n * `docker build <context>`).\n */\nfunction imageRequiresContext(image: Image): boolean {\n return image.buildOperations.some(opReferencesHostFiles);\n}\n\n// --- Public API ------------------------------------------------------------\n\nexport async function createSandboxImage(\n source: SandboxImageSource,\n options: CreateSandboxImageOptions = {},\n deps: CreateSandboxImageDeps = {},\n): Promise<Record<string, unknown>> {\n const emit = deps.emit ?? (options.verbose ? stderrEmit : noopEmit);\n const context = buildContextFromEnv();\n\n let dockerfilePath: string;\n let dockerfileText: string | undefined;\n let nativeContextDir: string | undefined;\n let effectiveName: string;\n // Throwaway empty build context created when an Image build has no explicit\n // contextDir. Removed in the finally below.\n let tempContextDir: string | undefined;\n\n if (source instanceof Image) {\n if (!source.baseImage) {\n throw new Error(\"Image must have a baseImage to build\");\n }\n // With an explicit contextDir we upload that directory as-is, like\n // `docker build <dir>`. Without one, an image that reads host files via\n // COPY/ADD can't be built (there is no context to resolve them against);\n // images without such ops get an empty context (just the Dockerfile) so\n // the whole cwd is not archived.\n let resolvedContext: string;\n if (options.contextDir != null) {\n resolvedContext = path.resolve(options.contextDir);\n } else if (imageRequiresContext(source)) {\n throw new Error(\n \"This image reads files from the host (via COPY/ADD or a RUN bind \" +\n \"mount), so it needs a build context. Pass `contextDir` pointing at \" +\n \"the directory that contains those sources; they resolve relative \" +\n \"to it, like `docker build <contextDir>`.\",\n );\n } else {\n tempContextDir = mkdtempSync(path.join(os.tmpdir(), \"tl-build-context-\"));\n resolvedContext = tempContextDir;\n }\n dockerfilePath = path.join(resolvedContext, \"Dockerfile\");\n let text = dockerfileContent(source);\n if (!text.endsWith(\"\\n\")) text += \"\\n\";\n dockerfileText = text;\n nativeContextDir = resolvedContext;\n effectiveName = options.registeredName ?? source.name;\n } else if (typeof source === \"string\") {\n const resolvedPath = path.resolve(source);\n if (!existsSync(resolvedPath)) {\n throw new Error(`Dockerfile not found: ${source}`);\n }\n dockerfilePath = resolvedPath;\n dockerfileText = undefined;\n nativeContextDir = undefined;\n effectiveName =\n options.registeredName ?? defaultRegisteredName(resolvedPath);\n } else {\n throw new TypeError(\n `source must be an Image or a Dockerfile path, got ${typeof source}`,\n );\n }\n\n try {\n if (effectiveName === DEFAULT_IMAGE_NAME) {\n console.warn(\n `Building sandbox image with the default name \"${DEFAULT_IMAGE_NAME}\". ` +\n \"Pass `registeredName` or `Image({ name })` to avoid collisions \" +\n \"with other default-named images in this project.\",\n );\n }\n\n const usePat = deps._allowPat === true && context.apiKey == null;\n const bearerToken = context.apiKey ?? (usePat ? context.personalAccessToken : undefined);\n if (!bearerToken) {\n if (context.personalAccessToken && !deps._allowPat) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\n deps._allowPat\n ? \"Missing TENSORLAKE_API_KEY or TENSORLAKE_PAT credentials.\"\n : \"Missing TENSORLAKE_API_KEY credentials.\",\n );\n }\n\n emit({ type: \"status\", message: `Building image '${effectiveName}'...` });\n\n const binding = loadNativeBinding();\n let emitError: unknown;\n const resultJson = await binding.buildSandboxImage(\n {\n apiUrl: context.apiUrl,\n bearerToken,\n dockerfilePath,\n registeredName: effectiveName,\n diskMb: options.diskMb,\n builderDiskMb: options.builderDiskMb,\n cpus: options.cpus,\n memoryMb: options.memoryMb,\n isPublic: options.isPublic ?? false,\n organizationId: usePat ? context.organizationId : undefined,\n projectId: usePat ? context.projectId : undefined,\n namespace: context.namespace,\n useScopeHeaders: usePat,\n userAgent: undefined,\n dockerCompat: options.dockerCompat ?? false,\n dockerfileText,\n contextDir: nativeContextDir,\n },\n (event) => {\n try {\n emit(eventToEmitDict(event));\n } catch (error) {\n emitError ??= error;\n }\n },\n );\n\n if (emitError != null) {\n throw emitError;\n }\n\n let result: Record<string, unknown> = {};\n if (resultJson.trim().length > 0) {\n result = JSON.parse(resultJson) as Record<string, unknown>;\n }\n emit({\n type: \"image_registered\",\n name: effectiveName,\n image_id:\n (typeof result.id === \"string\" && result.id) ||\n (typeof result.templateId === \"string\" && result.templateId) ||\n \"\",\n });\n emit({ type: \"done\" });\n return result;\n } finally {\n if (tempContextDir != null) {\n rmSync(tempContextDir, { recursive: true, force: true });\n }\n }\n}\n\n/**\n * Import a registry image directly into a sandbox image — no Docker.\n *\n * Unlike {@link createSandboxImage}, there is no Dockerfile and no build\n * context: the builder pulls the referenced image's layers and applies them\n * straight into the rootfs (via `oci-image-to-ext4`), bypassing the Docker\n * daemon entirely. This is the programmatic backend for the\n * `tl sbx image import` CLI command. The import is always a fresh base from\n * the registry — the reference is never resolved against the template\n * registry.\n */\nexport async function importSandboxImage(\n imageReference: string,\n options: ImportSandboxImageOptions = {},\n deps: CreateSandboxImageDeps = {},\n): Promise<Record<string, unknown>> {\n const emit = deps.emit ?? (options.verbose ? stderrEmit : noopEmit);\n\n if (typeof imageReference !== \"string\" || imageReference.trim().length === 0) {\n throw new Error(\"image reference to import must not be empty\");\n }\n const reference = imageReference.trim();\n\n const context = buildContextFromEnv();\n const effectiveName =\n options.registeredName ?? defaultRegisteredNameFromImage(reference);\n\n if (effectiveName === DEFAULT_IMAGE_NAME) {\n console.warn(\n `Importing sandbox image with the default name \"${DEFAULT_IMAGE_NAME}\". ` +\n \"Pass `registeredName` to avoid collisions with other default-named \" +\n \"images in this project.\",\n );\n }\n\n const usePat = deps._allowPat === true && context.apiKey == null;\n const bearerToken = context.apiKey ?? (usePat ? context.personalAccessToken : undefined);\n if (!bearerToken) {\n if (context.personalAccessToken && !deps._allowPat) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\n deps._allowPat\n ? \"Missing TENSORLAKE_API_KEY or TENSORLAKE_PAT credentials.\"\n : \"Missing TENSORLAKE_API_KEY credentials.\",\n );\n }\n\n emit({\n type: \"status\",\n message: `Importing image '${reference}' as '${effectiveName}'...`,\n });\n\n const binding = loadNativeBinding();\n let emitError: unknown;\n const resultJson = await binding.importSandboxImage(\n {\n apiUrl: context.apiUrl,\n bearerToken,\n imageReference: reference,\n registeredName: effectiveName,\n diskMb: options.diskMb,\n builderDiskMb: options.builderDiskMb,\n cpus: options.cpus,\n memoryMb: options.memoryMb,\n isPublic: options.isPublic ?? false,\n organizationId: usePat ? context.organizationId : undefined,\n projectId: usePat ? context.projectId : undefined,\n namespace: context.namespace,\n useScopeHeaders: usePat,\n userAgent: undefined,\n dockerCompat: options.dockerCompat ?? false,\n },\n (event) => {\n try {\n emit(eventToEmitDict(event));\n } catch (error) {\n emitError ??= error;\n }\n },\n );\n\n if (emitError != null) {\n throw emitError;\n }\n\n let result: Record<string, unknown> = {};\n if (resultJson.trim().length > 0) {\n result = JSON.parse(resultJson) as Record<string, unknown>;\n }\n emit({\n type: \"image_registered\",\n name: effectiveName,\n image_id:\n (typeof result.id === \"string\" && result.id) ||\n (typeof result.templateId === \"string\" && result.templateId) ||\n \"\",\n });\n emit({ type: \"done\" });\n return result;\n}\n\nexport async function deleteSandboxImage(imageName: string): Promise<void> {\n if (typeof imageName !== \"string\" || imageName.length === 0) {\n throw new TypeError(\"imageName must be a non-empty string\");\n }\n\n const context = buildContextFromEnv();\n const bearerToken = context.apiKey;\n if (!bearerToken) {\n if (context.personalAccessToken) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\"Missing TENSORLAKE_API_KEY credentials.\");\n }\n\n const client = new CloudClient({\n apiUrl: context.apiUrl,\n apiKey: bearerToken,\n namespace: context.namespace,\n });\n try {\n await client.deleteSandboxImage(imageName);\n } finally {\n client.close();\n }\n}\n\n/**\n * Look up a registered sandbox image by its registered name.\n *\n * Returns the registered sandbox template, or `null` if no image with that\n * name exists. Uses the same environment-based Tensorlake auth as\n * `createSandboxImage`. Ingress derives project scope from the API key.\n */\nexport async function findSandboxImageByName(\n imageName: string,\n): Promise<SandboxTemplate | null> {\n if (typeof imageName !== \"string\" || imageName.length === 0) {\n throw new TypeError(\"imageName must be a non-empty string\");\n }\n\n const context = buildContextFromEnv();\n const bearerToken = context.apiKey;\n if (!bearerToken) {\n if (context.personalAccessToken) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\"Missing TENSORLAKE_API_KEY credentials.\");\n }\n\n const client = new CloudClient({\n apiUrl: context.apiUrl,\n apiKey: bearerToken,\n namespace: context.namespace,\n });\n try {\n return await client.findSandboxImageByName(imageName);\n } finally {\n client.close();\n }\n}\n\n/**\n * List all registered sandbox images for the current project.\n *\n * Returns the registered sandbox templates (each with `id`, `name`,\n * `snapshotId`, `public`, etc.). Uses the same environment-based Tensorlake\n * auth as `createSandboxImage`. Ingress derives project scope from the API key.\n */\nexport async function listSandboxImages(): Promise<SandboxTemplate[]> {\n const context = buildContextFromEnv();\n const bearerToken = context.apiKey;\n if (!bearerToken) {\n if (context.personalAccessToken) {\n throw new Error(\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n );\n }\n throw new Error(\"Missing TENSORLAKE_API_KEY credentials.\");\n }\n\n const client = new CloudClient({\n apiUrl: context.apiUrl,\n apiKey: bearerToken,\n namespace: context.namespace,\n });\n try {\n return await client.listSandboxImages();\n } finally {\n client.close();\n }\n}\n\nexport async function runCreateSandboxImageCli(argv = process.argv.slice(2)) {\n const parsed = parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n name: { type: \"string\", short: \"n\" },\n cpus: { type: \"string\" },\n memory: { type: \"string\" },\n disk_mb: { type: \"string\" },\n builder_disk_mb: { type: \"string\" },\n docker_compat: { type: \"boolean\", default: false },\n public: { type: \"boolean\", default: false },\n },\n });\n\n const dockerfilePath = parsed.positionals[0];\n if (!dockerfilePath) {\n throw new Error(\n \"Usage: tensorlake-create-sandbox-image <dockerfile_path> [--name NAME] [--cpus N] [--memory MB] [--disk_mb MB] [--builder_disk_mb MB] [--docker_compat] [--public]\",\n );\n }\n\n const cpus =\n parsed.values.cpus != null ? Number(parsed.values.cpus) : undefined;\n const memoryMb =\n parsed.values.memory != null ? Number(parsed.values.memory) : undefined;\n const diskMb =\n parsed.values.disk_mb != null ? Number(parsed.values.disk_mb) : undefined;\n const builderDiskMb =\n parsed.values.builder_disk_mb != null\n ? Number(parsed.values.builder_disk_mb)\n : undefined;\n if (cpus != null && !Number.isFinite(cpus)) {\n throw new Error(`Invalid --cpus value: ${parsed.values.cpus}`);\n }\n if (memoryMb != null && !Number.isInteger(memoryMb)) {\n throw new Error(`Invalid --memory value: ${parsed.values.memory}`);\n }\n if (diskMb != null && !Number.isInteger(diskMb)) {\n throw new Error(`Invalid --disk_mb value: ${parsed.values.disk_mb}`);\n }\n if (builderDiskMb != null && !Number.isInteger(builderDiskMb)) {\n throw new Error(\n `Invalid --builder_disk_mb value: ${parsed.values.builder_disk_mb}`,\n );\n }\n\n await createSandboxImage(\n dockerfilePath,\n {\n registeredName: parsed.values.name,\n cpus,\n memoryMb,\n diskMb,\n builderDiskMb,\n dockerCompat: parsed.values.docker_compat,\n isPublic: parsed.values.public,\n },\n { emit: ndjsonStdoutEmit, _allowPat: true },\n );\n}\n\nexport async function runImportSandboxImageCli(argv = process.argv.slice(2)) {\n const parsed = parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n name: { type: \"string\", short: \"n\" },\n cpus: { type: \"string\" },\n memory: { type: \"string\" },\n disk_mb: { type: \"string\" },\n builder_disk_mb: { type: \"string\" },\n docker_compat: { type: \"boolean\", default: false },\n public: { type: \"boolean\", default: false },\n },\n });\n\n const imageReference = parsed.positionals[0];\n if (!imageReference) {\n throw new Error(\n \"Usage: tensorlake-import-sandbox-image <image_reference> [--name NAME] [--cpus N] [--memory MB] [--disk_mb MB] [--builder_disk_mb MB] [--docker_compat] [--public]\",\n );\n }\n\n const cpus =\n parsed.values.cpus != null ? Number(parsed.values.cpus) : undefined;\n const memoryMb =\n parsed.values.memory != null ? Number(parsed.values.memory) : undefined;\n const diskMb =\n parsed.values.disk_mb != null ? Number(parsed.values.disk_mb) : undefined;\n const builderDiskMb =\n parsed.values.builder_disk_mb != null\n ? Number(parsed.values.builder_disk_mb)\n : undefined;\n if (cpus != null && !Number.isFinite(cpus)) {\n throw new Error(`Invalid --cpus value: ${parsed.values.cpus}`);\n }\n if (memoryMb != null && !Number.isInteger(memoryMb)) {\n throw new Error(`Invalid --memory value: ${parsed.values.memory}`);\n }\n if (diskMb != null && !Number.isInteger(diskMb)) {\n throw new Error(`Invalid --disk_mb value: ${parsed.values.disk_mb}`);\n }\n if (builderDiskMb != null && !Number.isInteger(builderDiskMb)) {\n throw new Error(\n `Invalid --builder_disk_mb value: ${parsed.values.builder_disk_mb}`,\n );\n }\n\n await importSandboxImage(\n imageReference,\n {\n registeredName: parsed.values.name,\n cpus,\n memoryMb,\n diskMb,\n builderDiskMb,\n dockerCompat: parsed.values.docker_compat,\n isPublic: parsed.values.public,\n },\n { emit: ndjsonStdoutEmit, _allowPat: true },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACAA,IACa,aAEA,SAEA,SACA,WACA,mBAGA,yBACA,aACA,kBACA;AAbb;AAAA;AAAA;AAAA;AACO,IAAM,cAAsB;AAE5B,IAAM,UACX,QAAQ,IAAI,sBAAsB;AAC7B,IAAM,UAAU,QAAQ,IAAI,sBAAsB;AAClD,IAAM,YAAY,QAAQ,IAAI,sBAAsB;AACpD,IAAM,oBACX,QAAQ,IAAI,gCAAgC;AAEvC,IAAM,0BAA0B;AAChC,IAAM,cAAc;AACpB,IAAM,mBAAmB;AACzB,IAAM,yBAAyB,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AAAA;AAAA;;;AC+B3D,SAAS,cAAc,KAAsB;AAClD,QAAM,QAAkB,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AqB;AAAA;AAAA;","names":["path","value","path","createSandboxImage","detectLinuxLibc","fs","read","count","path","fileURLToPath","require","path","existsSync","DEFAULT_IMAGE_NAME"]}