@tensorlakeai/tensorlake 0.5.152 → 0.5.154

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/applications/index.cjs +3596 -3377
  2. package/dist/applications/index.cjs.map +1 -1
  3. package/dist/applications/index.d.cts +3 -3
  4. package/dist/applications/index.d.ts +3 -3
  5. package/dist/applications/index.js +3559 -3340
  6. package/dist/applications/index.js.map +1 -1
  7. package/dist/function-agent/main.cjs +1 -1
  8. package/dist/function-agent/main.js +1 -1
  9. package/dist/function-executor/main.cjs +2 -2
  10. package/dist/function-executor/main.js +2 -2
  11. package/dist/index.cjs +1502 -880
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +366 -21
  14. package/dist/index.d.ts +366 -21
  15. package/dist/index.js +1475 -871
  16. package/dist/index.js.map +1 -1
  17. package/dist/{remote-CC48cvYP.d.cts → remote-B3vn4tt1.d.cts} +1 -1
  18. package/dist/{remote-BbSrvgUn.d.ts → remote-DqBUuciu.d.ts} +1 -1
  19. package/dist/{sandbox-image-CAK_K7ND.d.cts → sandbox-image-BMiFlzAs.d.cts} +168 -13
  20. package/dist/{sandbox-image-CAK_K7ND.d.ts → sandbox-image-BMiFlzAs.d.ts} +168 -13
  21. package/dist/sandbox-image.cjs +437 -1300
  22. package/dist/sandbox-image.cjs.map +1 -1
  23. package/dist/sandbox-image.d.cts +1 -1
  24. package/dist/sandbox-image.d.ts +1 -1
  25. package/dist/sandbox-image.js +436 -1299
  26. package/dist/sandbox-image.js.map +1 -1
  27. package/package.json +7 -7
  28. package/runtime/function-executor/manifest.json +5 -5
  29. package/runtime/function-executor/package/dist/function-executor/main.js +2 -2
  30. package/runtime/function-executor/package/npm-shrinkwrap.json +2 -2
  31. package/runtime/function-executor/package/package.json +1 -1
  32. package/runtime/typescript-function-runner/manifest.json +5 -5
  33. package/runtime/typescript-function-runner/package/dist/function-agent/main.js +1 -1
  34. package/runtime/typescript-function-runner/package/npm-shrinkwrap.json +26 -26
  35. package/runtime/typescript-function-runner/package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/defaults.ts","../src/models.ts","../src/errors.ts","../src/native-worker-protocol.ts","../src/url.ts","../src/native-worker-client.ts","../src/native-sandbox.ts","../src/native-cloud.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;\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\n/**\n * Why a pending sandbox is waiting (`pendingReason`). The wire value is a\n * snake_case string; unknown future reasons arrive as plain strings.\n */\nexport enum SandboxPendingReason {\n SCHEDULING = \"scheduling\",\n WAITING_FOR_CONTAINER = \"waiting_for_container\",\n NO_EXECUTORS_AVAILABLE = \"no_executors_available\",\n NO_RESOURCES_AVAILABLE = \"no_resources_available\",\n POOL_AT_CAPACITY = \"pool_at_capacity\",\n MAX_CAPACITY_REACHED = \"max_capacity_reached\",\n NO_EXECUTOR_FOR_SNAPSHOT_LOCATION = \"no_executor_for_snapshot_location\",\n /** The autoscaler reported that no fleet can ever place this shape. */\n UNPLACEABLE = \"unplaceable\",\n}\n\n/** `terminationReason` when a `maxPendingSecs` bound expired, or the shape is unplaceable. */\nexport const TERMINATION_REASON_NO_CAPACITY = \"no_capacity\";\n/** `terminationReason` when a pending sandbox was deleted before it ran. */\nexport const TERMINATION_REASON_CANCELLED = \"cancelled\";\n\n/** Whether a sandbox status is one a readiness wait keeps polling through. */\nexport function isSandboxPending(status: SandboxStatus | string): boolean {\n return String(status) === SandboxStatus.PENDING;\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 the overlay-path constraints of non-CAS sandboxes.\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 diskMb: number;\n /** Reported GPU allocation. Include it in a pool update to retain the allocation. */\n gpuConfigs?: GPUResources[];\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 | \"RTX-PRO-6000\"\n | \"L40\"\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 MiB. Defaults to 1024 for fresh creates; snapshot restores inherit it when omitted. */\n memoryMb?: number;\n /** Root disk size in MiB. 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. Defaults to one GPU when gpus is omitted. 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 * `false` returns a `PendingSandbox` handle as soon as the sandbox is\n * durable, without waiting for it to run: `pending.ready()` waits,\n * `pending.status()` looks, and `Sandbox.connect(pending.sandboxId)`\n * collects it from any other process. `true` / unset waits as before.\n */\n wait?: boolean;\n /**\n * Longest the sandbox may wait for capacity before the server fails it with\n * reason `no_capacity`. `0` fails at once when it cannot be placed; unset\n * (the default) waits indefinitely. Applies to capacity waits only, not to\n * image pull or boot. A bound shorter than the fleet's boot time (up to 20\n * minutes on metal hosts) expires the very demand that made the autoscaler\n * launch a host; 30 minutes or more is recommended for capacity waits.\n */\n maxPendingSecs?: number;\n}\n\n/**\n * Bounded generation wait. Timeout never cancels a resize. Times are seconds.\n * A zero timeout checks once without polling again.\n */\nexport interface ResourceResizeWaitOptions {\n timeout?: number;\n pollInterval?: number;\n}\n\nexport enum ResizeStatus {\n PENDING = \"pending\",\n SUCCEEDED = \"succeeded\",\n FAILED = \"failed\",\n}\n\nexport enum ResizeErrorReason {\n FAILED = \"failed\",\n TIMEOUT = \"timeout\",\n SUPERSEDED = \"superseded\",\n INTERRUPTED = \"interrupted\",\n INCOMPATIBLE_RESPONSE = \"incompatible_response\",\n}\n\nexport interface SandboxResourceResizeInfo {\n generation: number;\n requested: ContainerResourcesInfo;\n status: ResizeStatus | (string & {});\n errorMessage?: string | null;\n}\n\n/** Wait options apply only to resource updates and are ignored for other properties. */\nexport interface UpdateSandboxOptions extends ResourceResizeWaitOptions {\n /** Whole live vCPU target; omitted retains the current allocation. */\n cpus?: number;\n /** Memory target in MiB, with the same units as create; never rounded by the SDK. */\n memoryMb?: number;\n /** Root disk target in MiB; can only grow. */\n diskMb?: number;\n /** Wait for resize completion (default true). False returns admission. */\n wait?: boolean;\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\n/**\n * Response from a blocking create or a pool claim.\n *\n * The server waits for readiness for at most the request timeout and can\n * already report `running`; a `pending` answer carries a `pendingReason`.\n * Use `connect(sandboxId)` to wait for a pending sandbox, or\n * `create({ wait: false })` for a `PendingSandbox` handle.\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 pendingReason?: string;\n}\n\n/**\n * The acknowledgement of a `create({ wait: false })`: the wire record of a\n * sandbox that is durable and starts whenever capacity allows. The\n * `PendingSandbox` class in `pending-sandbox.ts` wraps it with `ready()` /\n * `status()`. A server that predates `wait: false` answers the blocking\n * create's shape instead, so `state` may already be `running`.\n */\nexport interface PendingSandboxRecord {\n sandboxId: string;\n name?: string;\n state: SandboxStatus;\n pendingReason?: string;\n routingHint?: string;\n ingressEndpoint?: string;\n sandboxUrl?: string;\n reason?: string;\n terminationReason?: string;\n errorDetails?: unknown;\n}\n\nexport interface ReadyOptions {\n /** Seconds to wait; defaults to the client requestTimeout. `0` observes the current state once. */\n timeout?: number;\n /** Seconds between `GET /sandboxes/{id}` polls. Default: 2. */\n pollInterval?: number;\n /**\n * Delete the sandbox when `timeout` runs out while it is still pending,\n * then throw `SandboxError` (the pre-ADR-0086 behaviour). Default false:\n * throw `SandboxPending` and leave the sandbox queued.\n */\n cancelOnTimeout?: boolean;\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 runtime?: string;\n resourceResize?: SandboxResourceResizeInfo | null;\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 /** Egress network policy currently applied to the sandbox. */\n networkPolicy?: NetworkConfig;\n poolId?: string;\n outcome?: string;\n terminationReason?: string;\n errorDetails?: unknown;\n /** Why a pending sandbox is waiting, in snake_case. */\n pendingReason?: string;\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 /** Root disk size in MiB. Omit to use the registered image's size. */\n diskMb?: number;\n /** GPUs per container. Defaults to A10 unless gpuModel is set. GPU CAS pools require a CAS image. */\n gpus?: number;\n /** GPU model to allocate for each container. Defaults to one GPU when gpus is omitted. Validated at runtime. */\n gpuModel?: GpuModel | (string & {});\n /** Typed GPU allocation. Cannot be combined with gpus or gpuModel. */\n gpu?: GpuRequest;\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 /** Root disk size in MiB. Omit to use the registered image's size. */\n diskMb?: number;\n /** GPUs per container. Include on each update to keep a GPU CAS pool; omission configures a CPU-only CAS pool. Defaults to A10 unless gpuModel is set. */\n gpus?: number;\n /** GPU model to allocate for each container. Defaults to one GPU when gpus is omitted. Validated at runtime. */\n gpuModel?: GpuModel | (string & {});\n /** Typed GPU allocation. Cannot be combined with gpus or gpuModel. */\n gpu?: GpuRequest;\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\n/** Why a command run with `Sandbox.run()` ended. */\nexport enum CommandExitReason {\n /** The process exited on its own; `exitCode` is its exit status. */\n EXITED = \"exited\",\n /** The process was killed by a signal; `exitCode` is `-signal`. */\n SIGNALED = \"signaled\",\n /** The kernel OOM killer terminated the process (`exitCode` is `-9`). */\n OOM_KILLED = \"oom_killed\",\n /** The run's `timeout` expired and the sandbox killed the process (`exitCode` is `-9`). */\n TIMED_OUT = \"timed_out\",\n}\n\nexport interface CommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n /**\n * Why the command ended. `Sandbox.run()` always sets it; sandboxes that\n * predate timeout reporting never report `TIMED_OUT`, so a timed-out run on\n * them shows as `SIGNALED`.\n */\n reason?: CommandExitReason;\n /** True when the run's `timeout` expired and the process was killed. */\n timedOut?: boolean;\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 /**\n * HTTP request timeout in seconds. For a streamed response it bounds the\n * wait for the stream to start and each wait for more data. Default: 300.\n */\n requestTimeout?: number;\n /** @deprecated Use requestTimeout. 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 /**\n * Optional HTTP request timeout in seconds for sandbox proxy operations. For\n * streamed responses, such as `run()` and output follows, it bounds the wait\n * for the stream to start and each wait for more data. Omit for no proxy\n * timeout.\n */\n requestTimeout?: number;\n /** @deprecated Use requestTimeout. Optional 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 * Delete the sandbox when `requestTimeout` runs out while it is still\n * pending, then throw `SandboxError` (the pre-ADR-0086 behaviour). Default\n * false: throw `SandboxPending` and leave the sandbox queued.\n */\n cancelOnTimeout?: boolean;\n /** Seconds between readiness polls. Default: 2. */\n pollInterval?: 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","import type { ContainerResourcesInfo, ResizeErrorReason, SandboxInfo } from \"./models.js\";\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/**\n * General sandbox operation error.\n *\n * `reason` carries the server's reason when the error describes a sandbox\n * that failed or terminated: `no_capacity` when a `maxPendingSecs` bound\n * expired, `cancelled` when a pending sandbox was deleted, or a startup\n * reason such as `ConfigurationError`. It is undefined for errors that are\n * not about a sandbox's fate.\n */\nexport class SandboxError extends SandboxException {\n readonly reason?: string;\n readonly sandboxId?: string;\n\n constructor(\n message: string,\n options?: { reason?: string; sandboxId?: string },\n ) {\n super(message);\n this.name = \"SandboxError\";\n if (options?.reason !== undefined) this.reason = options.reason;\n if (options?.sandboxId !== undefined) this.sandboxId = options.sandboxId;\n }\n}\n\n/** A failed, timed-out, interrupted, or superseded resize, with confirmed allocation. */\nexport class SandboxResizeError extends SandboxError {\n declare readonly reason: ResizeErrorReason;\n readonly generation: number;\n readonly info?: SandboxInfo;\n\n constructor(payload: {\n sandboxId: string;\n generation: number;\n reason: ResizeErrorReason;\n message: string;\n info?: SandboxInfo | null;\n }) {\n const resources = payload.info?.resources;\n const allocation = resources\n ? `${resources.cpus} CPUs, ${resources.memoryMb} MiB memory, ${resources.diskMb} MiB disk`\n : \"unavailable\";\n super(\n `Sandbox ${payload.sandboxId} resize generation ${payload.generation}: ${payload.message}; last confirmed allocation: ${allocation}`,\n { reason: payload.reason, sandboxId: payload.sandboxId },\n );\n this.name = \"SandboxResizeError\";\n this.generation = payload.generation;\n this.info = payload.info ?? undefined;\n }\n\n /** Last confirmed allocation, if an observation was available. */\n get confirmedResources(): ContainerResourcesInfo | undefined {\n return this.info?.resources;\n }\n}\n\n/**\n * The wait budget ran out while the sandbox was still queued.\n *\n * Thrown by `Sandbox.create`, `createAndConnect`, `PendingSandbox.ready` and\n * a lazy `connect` when their timeout elapses before the sandbox is running.\n * **The sandbox is not deleted**: it keeps its place in the queue and starts\n * whenever capacity arrives. Call `ready()` again to keep waiting,\n * `Sandbox.connect` from any other process, or `delete` it to give up.\n * `pendingReason` is the last reason the scheduler recorded (`scheduling`,\n * `no_resources_available`, `pool_at_capacity`, ...).\n */\nexport class SandboxPending extends SandboxError {\n declare readonly sandboxId: string;\n readonly pendingReason?: string;\n readonly timeout?: number;\n\n constructor(\n sandboxId: string,\n options?: { pendingReason?: string; timeout?: number },\n ) {\n let message = `Sandbox ${sandboxId} is still pending`;\n if (options?.timeout !== undefined) message += ` after ${options.timeout}s`;\n if (options?.pendingReason) message += ` (${options.pendingReason})`;\n message +=\n \"; it keeps its place in the queue. Wait again with ready() or \" +\n `Sandbox.connect({ sandboxId: '${sandboxId}' }), or delete it to cancel.`;\n super(message, { reason: options?.pendingReason, sandboxId });\n this.name = \"SandboxPending\";\n this.pendingReason = options?.pendingReason;\n this.timeout = options?.timeout;\n }\n}\n\n/**\n * Raised when the client cannot complete a request against the API server.\n *\n * The original transport error 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. Transport\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 declare readonly sandboxId: string;\n\n constructor(sandboxId: string) {\n super(`Sandbox not found: ${sandboxId}`, { sandboxId });\n this.name = \"SandboxNotFoundError\";\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 declare readonly sandboxId?: string;\n /** Server reason, including unknown future reasons. */\n declare 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 reason,\n sandboxId,\n });\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","/** Internal protocol. Native objects never cross an isolate boundary. */\nexport type NativeClientKind =\n | \"NativeCloudClient\"\n | \"NativeSandboxClient\"\n | \"NativeSandboxProxyClient\"\n | \"NativeTcpTunnel\"\n | \"NativeRepositoryClient\";\n\nexport interface NativeHandle {\n id: number;\n kind: NativeClientKind;\n args: unknown[];\n parent?: NativeHandle;\n}\n\nexport type WorkerRequest =\n | { type: \"create\"; handle: Omit<NativeHandle, \"parent\">; parentId?: number }\n | {\n type: \"call\";\n id: number;\n handleId?: number;\n method: string;\n args: unknown[];\n stream: boolean;\n }\n | { type: \"release\"; handleId: number }\n | { type: \"ack\" | \"cancel\"; id: number };\n\nexport type WorkerResponse =\n | { type: \"result\"; id: number; value: unknown }\n | {\n type: \"error\";\n id: number;\n error: { name: string; message: string; stack?: string };\n }\n | { type: \"event\"; id: number; value: string };\n\nexport const cancelNativeCall = Symbol.for(\"tensorlake.native.cancel.v1\");\nexport const closeNativeHandle = Symbol.for(\"tensorlake.native.close.v1\");\nexport type NativeCall<T> = Promise<T> & { [cancelNativeCall]?: () => void };\n","import * as defaults from \"./defaults.js\";\n\n/** Remove a trailing slash from a URL string if present. */\nfunction trimTrailingSlashes(url: string): string {\n return url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\n\n/** Check whether a URL points to localhost. */\nexport function isLocalhost(apiUrl: string): boolean {\n try {\n const parsed = new URL(apiUrl);\n return parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n return false;\n }\n}\n\n/** Return the explicit sandbox proxy env override, if the user set one. */\nexport function explicitProxyUrlOverride(): string | undefined {\n const explicit = process.env.TENSORLAKE_SANDBOX_PROXY_URL?.trim();\n return explicit && explicit.length > 0 ? explicit : undefined;\n}\n\n/**\n * Resolve the legacy default proxy URL for direct sandbox handles.\n *\n * Normal client connect/create flows use the server-returned `sandboxUrl`.\n * This helper keeps the old direct-handle behavior and treats the env var as\n * an explicit override.\n *\n * Legacy priority:\n * 1. TENSORLAKE_SANDBOX_PROXY_URL env var\n * 2. `http://localhost:9443` for localhost API URLs\n * 3. Transform `api.X` → `sandbox.X`\n * 4. Default fallback\n */\nexport function resolveProxyUrl(apiUrl: string): string {\n const explicit = explicitProxyUrlOverride();\n if (explicit) return explicit;\n\n if (isLocalhost(apiUrl)) return \"http://localhost:9443\";\n\n try {\n const parsed = new URL(apiUrl);\n const host = parsed.hostname;\n if (host.startsWith(\"api.\")) {\n const proxyHost = \"sandbox.\" + host.slice(4);\n return `${parsed.protocol}//${proxyHost}`;\n }\n } catch {\n // fall through to default\n }\n\n return defaults.SANDBOX_PROXY_URL;\n}\n\n/**\n * Resolve the proxy target for a specific sandbox.\n *\n * - Localhost: base URL stays the same, Host header set to `{sandboxId}.local`\n * - Cloud: selected proxy domain with `X-Tensorlake-Sandbox-Id` header\n *\n * Returns `{ baseUrl, hostHeader, sandboxIdHeader }`.\n */\nexport function resolveProxyTarget(\n proxyUrl: string,\n sandboxId: string,\n): { baseUrl: string; hostHeader: string | undefined; sandboxIdHeader: string | undefined } {\n try {\n const parsed = new URL(proxyUrl);\n const host = parsed.hostname;\n\n if (host === \"localhost\" || host === \"127.0.0.1\") {\n return {\n baseUrl: trimTrailingSlashes(proxyUrl),\n hostHeader: `${sandboxId}.local`,\n sandboxIdHeader: undefined,\n };\n }\n\n const port = parsed.port ? `:${parsed.port}` : \"\";\n return {\n baseUrl: `${parsed.protocol}//${host}${port}`,\n hostHeader: undefined,\n sandboxIdHeader: sandboxId,\n };\n } catch {\n return {\n baseUrl: `${trimTrailingSlashes(proxyUrl)}/${sandboxId}`,\n hostHeader: undefined,\n sandboxIdHeader: undefined,\n };\n }\n}\n\n/**\n * Build a public sandbox URL from a server-provided ingress endpoint.\n *\n * `port` omitted or `9501` returns the management URL:\n * `https://<sandbox-id>.<ingress-host>`. User ports use the public\n * `<port>-<sandbox-id>.<ingress-host>` form.\n */\nexport function sandboxUrlFromIngressEndpoint(\n ingressEndpoint: string,\n sandboxId: string,\n port = 9501,\n): string {\n const parsed = new URL(ingressEndpoint);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new Error(\"ingressEndpoint must be an absolute http(s) URL\");\n }\n const label = port === 9501 ? sandboxId : `${port}-${sandboxId}`;\n return `${parsed.protocol}//${label}.${parsed.host}`;\n}\n\n/**\n * Derive the sandbox lifecycle URL from the API URL.\n *\n * Transforms `api.X` → `sandbox.X` for cloud. Returns the URL unchanged for\n * localhost or unrecognised patterns.\n */\nexport function resolveSandboxLifecycleUrl(apiUrl: string): string {\n if (isLocalhost(apiUrl)) return apiUrl;\n\n try {\n const parsed = new URL(apiUrl);\n if (parsed.hostname.startsWith(\"api.\")) {\n parsed.hostname = \"sandbox.\" + parsed.hostname.slice(4);\n return parsed.toString().replace(/\\/$/, \"\");\n }\n } catch {\n // fall through\n }\n\n return apiUrl;\n}\n\n/**\n * Build a lifecycle API path.\n *\n * - Localhost (namespaced): `/v1/namespaces/{namespace}/{path}`\n * - Cloud (flat): `/{path}`\n */\nexport function lifecyclePath(\n path: string,\n isLocal: boolean,\n namespace: string,\n): string {\n if (isLocal) {\n return `/v1/namespaces/${namespace}/${path}`;\n }\n return `/${path}`;\n}\n","import { createRequire } from \"node:module\";\nimport { Worker } from \"node:worker_threads\";\nimport type { NativeEmit, NativeSandboxBinding } from \"./native-sandbox.js\";\nimport {\n cancelNativeCall,\n closeNativeHandle,\n type NativeCall,\n type NativeHandle,\n type WorkerRequest,\n type WorkerResponse,\n} from \"./native-worker-protocol.js\";\nimport { resolveProxyTarget } from \"./url.js\";\n\ninterface PendingCall {\n resolve: (value: any) => void;\n reject: (error: Error) => void;\n emit?: NativeEmit;\n // Keep descriptors (and their parents) alive until the operation settles.\n handle?: NativeHandle;\n}\n\n/** One persistent worker per SDK installation and calling isolate. */\nexport class NativeWorkerClient {\n private worker?: Worker;\n private nextId = 1;\n private registered = new Set<number>();\n private pending = new Map<number, PendingCall>();\n private finalizers = new FinalizationRegistry<number>((id) =>\n this.release(id),\n );\n\n constructor(\n private readonly workerPath: () => string | URL = () =>\n createRequire(import.meta.url).resolve(\n \"@tensorlakeai/tensorlake/internal/native-worker\",\n ),\n ) {}\n\n handle(\n kind: NativeHandle[\"kind\"],\n args: unknown[],\n parent?: NativeHandle,\n ): object {\n const handle: NativeHandle = { id: this.nextId++, kind, args, parent };\n this.finalizers.register(handle, handle.id);\n let closed = false;\n return new Proxy(\n {},\n {\n get: (_target, method) => {\n if (method === \"then\") return undefined;\n if (method === closeNativeHandle)\n return () => {\n closed = true;\n this.release(handle.id);\n };\n if (method === \"connectProxy\")\n return (...proxyArgs: unknown[]) => {\n if (closed) throw new Error(\"Tensorlake native client is closed\");\n return this.handle(\"NativeSandboxProxyClient\", proxyArgs, handle);\n };\n if (method === \"baseUrl\")\n return () =>\n resolveProxyTarget(String(args[0]), String(args[1])).baseUrl;\n if (typeof method !== \"string\") return undefined;\n return (...callArgs: unknown[]) => {\n if (closed)\n return Promise.reject(\n new Error(\"Tensorlake native client is closed\"),\n );\n const emit =\n typeof callArgs.at(-1) === \"function\"\n ? (callArgs.pop() as NativeEmit)\n : undefined;\n return this.call(handle, method, callArgs, emit);\n };\n },\n },\n );\n }\n\n call(\n handle: NativeHandle | undefined,\n method: string,\n args: unknown[],\n emit?: NativeEmit,\n ): NativeCall<any> {\n const id = this.nextId++;\n let worker: Worker | undefined;\n const promise: NativeCall<any> = new Promise((resolve, reject) => {\n try {\n worker = this.getWorker();\n this.pending.set(id, { resolve, reject, emit, handle });\n worker.ref();\n if (handle) this.register(handle, worker);\n this.send(worker, {\n type: \"call\",\n id,\n handleId: handle?.id,\n method,\n args,\n stream: !!emit,\n });\n } catch (error) {\n this.pending.delete(id);\n this.unrefIfIdle();\n reject(error);\n }\n });\n promise[cancelNativeCall] = () => {\n const pending = this.pending.get(id);\n if (pending && worker) {\n pending.emit = undefined;\n this.send(worker, { type: \"cancel\", id });\n }\n };\n return promise;\n }\n\n private getWorker(): Worker {\n if (this.worker) return this.worker;\n const worker = new Worker(this.workerPath(), {\n // The bundled worker needs no application loaders or telemetry preloads.\n // NODE_OPTIONS is parsed independently of execArgv by Node.\n execArgv: [],\n env: { ...process.env, NODE_OPTIONS: \"\" },\n name: \"tensorlake-native\",\n });\n this.worker = worker;\n worker.on(\"message\", (message: WorkerResponse) => {\n const pending = this.pending.get(message.id);\n if (!pending || this.worker !== worker) return;\n if (message.type === \"event\") {\n // Acknowledge only when the consumer asks for the next event. At most\n // one event per stream is outstanding across Rust, worker and caller.\n Promise.resolve()\n .then(() => pending.emit?.(message.value))\n .then(\n () => {\n if (this.worker === worker)\n this.send(worker, { type: \"ack\", id: message.id });\n },\n (error: Error) => {\n this.send(worker, { type: \"cancel\", id: message.id });\n pending.reject(error);\n },\n );\n return;\n }\n this.pending.delete(message.id);\n if (message.type === \"error\") {\n const error = new Error(message.error.message);\n error.name = message.error.name;\n error.stack = message.error.stack ?? error.stack;\n pending.reject(error);\n } else {\n pending.resolve(message.value);\n }\n this.unrefIfIdle();\n });\n const fail = (error: Error) => {\n if (this.worker !== worker) return;\n this.worker = undefined;\n this.registered.clear();\n for (const pending of this.pending.values()) pending.reject(error);\n this.pending.clear();\n // Never replay an in-flight request: it may already have taken effect.\n // A subsequent explicit call starts a fresh worker from descriptors.\n void worker.terminate();\n };\n worker.on(\"error\", fail);\n worker.on(\"messageerror\", fail);\n worker.on(\"exit\", (code) =>\n fail(\n new Error(\n `Tensorlake native worker exited (${code}); in-flight operations were not retried`,\n ),\n ),\n );\n worker.unref();\n return worker;\n }\n\n private register(handle: NativeHandle, worker: Worker): void {\n if (this.registered.has(handle.id)) return;\n if (handle.parent) this.register(handle.parent, worker);\n this.send(worker, {\n type: \"create\",\n handle: { id: handle.id, kind: handle.kind, args: handle.args },\n parentId: handle.parent?.id,\n });\n this.registered.add(handle.id);\n }\n\n private release(handleId: number): void {\n if (this.worker && this.registered.delete(handleId))\n this.send(this.worker, { type: \"release\", handleId });\n }\n\n private send(worker: Worker, message: WorkerRequest): void {\n worker.postMessage(message);\n }\n private unrefIfIdle(): void {\n if (this.pending.size === 0) this.worker?.unref();\n }\n}\n\nexport function createWorkerBinding(\n runtime: NativeWorkerClient,\n): NativeSandboxBinding {\n return {\n NativeCloudClient: class {\n constructor(...args: unknown[]) {\n return runtime.handle(\"NativeCloudClient\", args);\n }\n },\n NativeSandboxClient: class {\n constructor(...args: unknown[]) {\n return runtime.handle(\"NativeSandboxClient\", args);\n }\n },\n NativeSandboxProxyClient: class {\n constructor(...args: unknown[]) {\n return runtime.handle(\"NativeSandboxProxyClient\", args);\n }\n },\n NativeRepositoryClient: class {\n constructor(...args: unknown[]) {\n return runtime.handle(\"NativeRepositoryClient\", args);\n }\n },\n NativeTcpTunnel: class {\n constructor() {\n return runtime.handle(\"NativeTcpTunnel\", []);\n }\n },\n validateManagedName: (name: string) =>\n runtime.call(undefined, \"validateManagedName\", [name]),\n } as unknown as NativeSandboxBinding;\n}\n\n// ESM and CJS can coexist in one application. Share the worker across bundles\n// of this SDK version, while keeping incompatible installed versions separate.\ndeclare const __SDK_VERSION__: string;\nconst runtimeKey = Symbol.for(\n `tensorlake.native.worker.${typeof __SDK_VERSION__ === \"undefined\" ? \"source\" : __SDK_VERSION__}.v1`,\n);\nconst runtimes = globalThis as typeof globalThis & {\n [runtimeKey]?: NativeWorkerClient;\n};\nexport function workerBinding(): NativeSandboxBinding {\n return createWorkerBinding(\n (runtimes[runtimeKey] ??= new NativeWorkerClient()),\n );\n}\n\n/** Runtime capsules supply the worker alongside their bundled application SDK. */\nexport function configureNativeWorker(workerPath: () => string | URL): void {\n runtimes[runtimeKey] ??= new NativeWorkerClient(workerPath);\n}\n\nexport function releaseNativeHandle(handle: object | null): void {\n (handle as { [closeNativeHandle]?: () => void } | null)?.[\n closeNativeHandle\n ]?.();\n}\n","import { CommandExitReason, fromSnakeKeys } from \"./models.js\";\nimport {\n PoolInUseError,\n PoolNotFoundError,\n RemoteAPIError,\n SandboxConnectionError,\n SandboxError,\n SandboxResizeError,\n SandboxNotFoundError,\n} from \"./errors.js\";\nimport { workerBinding } from \"./native-worker-client.js\";\nimport type { NativeCloudClient } from \"./native-cloud.js\";\nimport { cancelNativeCall, type NativeCall } from \"./native-worker-protocol.js\";\n\n/**\n * Bridge to the Rust core's sandbox lifecycle + proxy clients (`napi-rs`).\n *\n * The proxy data path (process/file/stream ops) is served by the Rust core so\n * it shares `reqwest`'s connection pool — replacing the previous undici path,\n * which multiplexed every parallel request onto a single, untuned HTTP/2\n * connection. The native binding is required: there is no JS fallback.\n *\n * Convention (mirrors the Python binding): structured payloads cross as JSON\n * strings, bytes as `Buffer`, and every call surfaces the W3C `traceId`.\n * Errors arrive as a JSON `{category, status, message}` string in the native\n * error message; {@link translateNativeError} rethrows them as the SDK's typed\n * errors.\n */\n\n// ---- Native value shapes --------------------------------------------------\n\nexport interface TracedJson {\n traceId: string;\n json: string;\n}\n\nexport interface TracedBytes {\n traceId: string;\n data: Uint8Array;\n contentId?: string;\n fullSize?: number;\n}\n\nexport interface TracedEvents {\n traceId: string;\n events: string[];\n}\n\n/** Per-event callback used by the streaming proxy methods. */\nexport type NativeEmit = (eventJson: string) => void | Promise<void>;\n\nexport interface NativeSandboxProxyClient {\n baseUrl(): string;\n\n startProcess(payloadJson: string): Promise<TracedJson>;\n listProcesses(): Promise<TracedJson>;\n // `process` is the pid-or-name path segment (the TS layer stringifies the number|string arg).\n getProcess(process: string): Promise<TracedJson>;\n killProcess(process: string): Promise<string>;\n restartProcess(process: string): Promise<TracedJson>;\n sendSignal(process: string, signal: number): Promise<TracedJson>;\n writeStdin(process: string, data: Buffer): Promise<string>;\n closeStdin(process: string): Promise<string>;\n getStdout(process: string): Promise<TracedJson>;\n getStderr(process: string): Promise<TracedJson>;\n getOutput(process: string): Promise<TracedJson>;\n\n followStdout(process: string, emit: NativeEmit): Promise<string>;\n followStderr(process: string, emit: NativeEmit): Promise<string>;\n followOutput(process: string, emit: NativeEmit): Promise<string>;\n runProcess(payloadJson: string): Promise<TracedEvents>;\n runProcessStreaming(payloadJson: string, emit: NativeEmit): Promise<string>;\n\n readFile(path: string): Promise<TracedBytes>;\n writeFile(path: string, content: Buffer): Promise<string>;\n uploadFile(path: string, localPath: string): Promise<string>;\n deleteFile(path: string): Promise<string>;\n listDirectory(path: string): Promise<TracedJson>;\n\n createPtySession(payloadJson: string): Promise<TracedJson>;\n deletePtySession(sessionId: string): Promise<string>;\n health(): Promise<TracedJson>;\n info(): Promise<TracedJson>;\n}\n\nexport interface NativeSandboxClient {\n createSandbox(requestJson: string): Promise<TracedJson>;\n /** Wait-free create (`wait: false`, ADR 0086). */\n createSandboxNoWait(requestJson: string): Promise<TracedJson>;\n /** Poll the sandbox until it leaves `pending` or the budget runs out; resolves with the last `SandboxInfo`. */\n waitForSandbox(\n sandboxId: string,\n timeoutSec: number,\n pollIntervalSec?: number | null,\n ): Promise<TracedJson>;\n claimSandbox(poolId: string, requestJson?: string): Promise<TracedJson>;\n copySandbox(sandboxId: string, times: number): Promise<TracedJson>;\n getSandbox(sandboxId: string): Promise<TracedJson>;\n listSandboxes(): Promise<TracedJson>;\n listArchivedSandboxes(\n limit?: number | null,\n cursor?: string | null,\n direction?: string | null,\n ): Promise<TracedJson>;\n getArchivedSandbox(sandboxId: string): Promise<TracedJson>;\n getSandboxLogs(requestJson: string): Promise<TracedJson>;\n listSandboxLogProcesses(sandboxId: string): Promise<TracedJson>;\n updateSandbox(\n sandboxId: string, requestJson: string, wait?: boolean,\n timeoutSec?: number, pollIntervalSec?: number,\n ): Promise<TracedJson>;\n waitForResourceResize(\n sandboxId: string, generation: number,\n timeoutSec?: number, pollIntervalSec?: number,\n ): Promise<TracedJson>;\n deleteSandbox(sandboxId: string): Promise<string>;\n suspendSandbox(sandboxId: string): Promise<string>;\n resumeSandbox(sandboxId: string): Promise<string>;\n attachFileSystem(\n sandboxId: string,\n fileSystemId: string,\n mountPath: string,\n readOnly?: boolean | null,\n prefetch?: boolean | null,\n snapshotId?: string | null,\n owner?: string | null,\n ): Promise<TracedJson>;\n detachFileSystem(\n sandboxId: string,\n mountPath: string,\n ): Promise<TracedJson>;\n createSnapshot(\n sandboxId: string,\n snapshotType?: string | null,\n ): Promise<TracedJson>;\n getSnapshot(snapshotId: string): Promise<TracedJson>;\n listSnapshots(): Promise<TracedJson>;\n deleteSnapshot(snapshotId: string): Promise<string>;\n createPool(requestJson: string): Promise<TracedJson>;\n getPool(poolId: string): Promise<TracedJson>;\n listPools(): Promise<TracedJson>;\n updatePool(poolId: string, requestJson: string): Promise<TracedJson>;\n deletePool(poolId: string): Promise<string>;\n\n connectProxy(\n proxyUrl: string,\n sandboxId: string,\n routingHint?: string | null,\n requestTimeoutSec?: number | null,\n ): NativeSandboxProxyClient;\n selectSandboxProxyUrl(\n sandboxId: string,\n sandboxUrl?: string | null,\n ingressEndpoint?: string | null,\n explicitProxyUrl?: string | null,\n ): string | Promise<string>;\n}\n\nexport interface NativeRepositoryClient {\n gitRepoUrl(repo: string): Promise<string>;\n createRepo(repo: string, defaultBranch?: string | null): Promise<TracedJson>;\n listRepos(): Promise<TracedJson>;\n deleteRepo(repo: string): Promise<string>;\n forkRepo(repo: string, baseRepo: string): Promise<TracedJson>;\n archiveRepo(repo: string): Promise<string>;\n restoreRepo(repo: string): Promise<string>;\n repoInfo(repo: string): Promise<TracedJson>;\n listBranches(repo: string): Promise<TracedJson>;\n listRefs(repo: string): Promise<TracedJson>;\n deleteBranch(repo: string, branch: string): Promise<string>;\n listOperations(repo: string): Promise<TracedJson>;\n gitCredential(repo?: string | null): Promise<string>;\n commitStatus(repo: string, jobId: string): Promise<TracedJson>;\n pushWorktree(\n repo: string,\n root: string,\n branch: string,\n message: string,\n expectOid?: string | null,\n ): Promise<TracedJson>;\n mergeRepo(\n repo: string,\n ours: string,\n theirs: string,\n preflight: boolean,\n deep: boolean,\n materialize: boolean,\n message?: string | null,\n base?: string | null,\n ): Promise<TracedJson>;\n commitConflicts(repo: string, commit: string): Promise<TracedJson>;\n createFilesystem(name: string, region?: string): Promise<string>;\n forkFilesystem(\n name: string,\n base: string,\n snapshot?: string | null,\n ): Promise<TracedJson>;\n listFilesystems(): Promise<TracedJson>;\n filesystemMeta(name: string): Promise<TracedJson>;\n deleteFilesystem(name: string): Promise<string>;\n filesystemRefStatus(name: string, refspec: string): Promise<TracedJson>;\n retainFilesystemSnapshot(\n name: string,\n message: string,\n requestId: string,\n ): Promise<TracedJson>;\n listFilesystemSnapshots(name: string): Promise<TracedJson>;\n deleteFilesystemSnapshot(name: string, snapshot: string): Promise<string>;\n readFilesystemFile(\n name: string,\n path: string,\n version: string,\n offset?: number,\n length?: number,\n ): Promise<TracedBytes>;\n listFilesystemTree(\n name: string,\n dirPath: string,\n version: string,\n ): Promise<TracedJson>;\n pushFilesystemFiles(\n name: string,\n files: Array<{ path: string; content: Buffer }>,\n deletes: string[],\n moves: Array<{ from: string; to: string }>,\n copies: Array<{ from: string; to: string }>,\n message: string,\n branch: string,\n idempotencyKey?: string | null,\n ): Promise<TracedJson>;\n pushFilesystemPaths(\n name: string,\n files: Array<{ path: string; localPath: string }>,\n message: string,\n branch: string,\n idempotencyKey?: string | null,\n ): Promise<TracedJson>;\n}\n\ninterface NativeSandboxClientCtor {\n new (\n apiUrl: string,\n apiKey?: string | null,\n organizationId?: string | null,\n projectId?: string | null,\n namespace?: string | null,\n userAgent?: string | null,\n requestTimeoutSec?: number | null,\n ): NativeSandboxClient;\n}\n\ninterface NativeRepositoryClientCtor {\n new (\n apiUrl: string,\n apiKey?: string | null,\n organizationId?: string | null,\n projectId?: string | null,\n userAgent?: string | null,\n requestTimeoutSec?: number | null,\n ): NativeRepositoryClient;\n}\n\ninterface NativeSandboxProxyClientCtor {\n new (\n proxyUrl: string,\n sandboxId: string,\n apiKey?: string | null,\n organizationId?: string | null,\n projectId?: string | null,\n routingHint?: string | null,\n userAgent?: string | null,\n requestTimeoutSec?: number | null,\n ): NativeSandboxProxyClient;\n}\n\nexport interface NativeSandboxBinding {\n NativeTcpTunnel: new () => NativeTcpTunnel;\n NativeCloudClient?: new (optionsJson: string) => NativeCloudClient;\n NativeSandboxClient: NativeSandboxClientCtor;\n NativeSandboxProxyClient: NativeSandboxProxyClientCtor;\n NativeRepositoryClient?: NativeRepositoryClientCtor;\n /** Validate a managed-process name; throws on failure. Single source-of-truth rule in Rust. */\n validateManagedName: (name: string) => void | Promise<void>;\n}\n\nexport interface NativeTcpTunnel {\n listen(\n baseUrl: string,\n headers: Record<string, string>,\n remotePort: number,\n localHost: string,\n localPort: number,\n timeout: number,\n ): Promise<number>;\n close(): Promise<void>;\n waitClosed(): Promise<void>;\n}\n\n// ---- Binding loader -------------------------------------------------------\n\nlet cachedBinding: NativeSandboxBinding | undefined;\nexport function loadNativeSandboxBinding(): NativeSandboxBinding {\n return cachedBinding ??= workerBinding();\n}\n\n/** Test seam: replace (or clear) the native binding. */\nexport function __setNativeSandboxBindingForTest(\n binding: NativeSandboxBinding | undefined,\n): void {\n cachedBinding = binding;\n}\n\n// ---- Error translation ----------------------------------------------------\n\ninterface NativeErrorPayload {\n category: string;\n status: number | null;\n message: string;\n}\n\n/** Context used to reconstruct entity-specific typed errors from a 404/409. */\nexport interface NativeErrorContext {\n sandboxId?: string;\n poolId?: string;\n /**\n * When set, a 404 maps to the typed not-found error for that entity\n * (`SandboxNotFoundError` / `PoolNotFoundError`). Lifecycle ops set it;\n * proxy/data-plane ops omit it so a 404 (e.g. missing file or process)\n * stays a generic `RemoteAPIError`, matching the pre-shim behavior.\n */\n notFoundKind?: \"sandbox\" | \"pool\";\n}\n\nfunction parseNativeError(error: unknown): NativeErrorPayload | null {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\";\n if (!message) return null;\n try {\n const parsed = JSON.parse(message) as Partial<NativeErrorPayload>;\n if (parsed && typeof parsed.category === \"string\") {\n return {\n category: parsed.category,\n status: typeof parsed.status === \"number\" ? parsed.status : null,\n message: typeof parsed.message === \"string\" ? parsed.message : message,\n };\n }\n } catch {\n // Not a structured native error — fall through.\n }\n return null;\n}\n\n/**\n * Map a native error to the SDK's typed error hierarchy, matching the status\n * codes the undici path produced (404 → SandboxNotFoundError/PoolNotFoundError,\n * 409 → PoolInUseError, connection failures → SandboxConnectionError).\n */\nexport function translateNativeError(\n error: unknown,\n context?: NativeErrorContext,\n): Error {\n const payload = parseNativeError(error);\n if (!payload) {\n if (error instanceof Error) return error;\n return new SandboxError(String(error));\n }\n\n const { category, status, message } = payload;\n\n if (category === \"resize\") {\n return new SandboxResizeError(\n fromSnakeKeys(JSON.parse(message), \"sandboxId\") as ConstructorParameters<typeof SandboxResizeError>[0],\n );\n }\n if (category === \"connection\") {\n return new SandboxConnectionError(message, { cause: error });\n }\n\n if (status === 404) {\n if (context?.notFoundKind === \"pool\" && context.poolId) {\n return new PoolNotFoundError(context.poolId);\n }\n if (context?.notFoundKind === \"sandbox\" && context.sandboxId) {\n return new SandboxNotFoundError(context.sandboxId);\n }\n return new RemoteAPIError(404, message);\n }\n\n if (status === 409 && context?.poolId) {\n return new PoolInUseError(context.poolId, message);\n }\n\n if (typeof status === \"number\") {\n return new RemoteAPIError(status, message);\n }\n\n return new SandboxError(message);\n}\n\n/** Run a native call, translating any error to the SDK's typed hierarchy. */\nexport async function callNative<T>(\n fn: () => Promise<T>,\n context?: NativeErrorContext,\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw translateNativeError(error, context);\n }\n}\n\n// ---- Streaming bridge -----------------------------------------------------\n\n/**\n * Adapt the native per-event callback API into an async generator, preserving\n * the live-streaming semantics of `followStdout`/`followStderr`/`followOutput`.\n * The native `start` call resolves once the upstream stream closes. Each emit\n * resolves only after consumption, propagating backpressure through the worker\n * to Rust. Cancellation drops the upstream response, including quiet streams.\n */\nexport async function* nativeEventStream(\n start: (emit: NativeEmit) => Promise<string>,\n context?: NativeErrorContext,\n signal?: AbortSignal,\n): AsyncGenerator<Record<string, unknown>> {\n if (signal?.aborted) return;\n const queue: Array<{ value: string; consumed: () => void }> = [];\n let wake: (() => void) | undefined;\n let finished = false;\n let stopped = false;\n let failure: unknown;\n const notify = () => { const resolve = wake; wake = undefined; resolve?.(); };\n const emit: NativeEmit = (value) => {\n if (stopped) return Promise.resolve();\n return new Promise<void>((consumed) => { queue.push({ value, consumed }); notify(); });\n };\n let call: NativeCall<string> | undefined;\n const onAbort = () => { stopped = true; call?.[cancelNativeCall]?.(); notify(); };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n call = start(emit);\n void call.catch((error: unknown) => { failure = error; }).finally(() => { finished = true; notify(); });\n while (!stopped) {\n const event = queue.shift();\n if (event) {\n try { yield JSON.parse(event.value) as Record<string, unknown>; }\n finally { event.consumed(); }\n } else if (finished) {\n break;\n } else {\n await new Promise<void>((resolve) => { wake = resolve; });\n }\n }\n if (!stopped && failure !== undefined) throw translateNativeError(failure, context);\n } finally {\n stopped = true;\n signal?.removeEventListener(\"abort\", onAbort);\n call?.[cancelNativeCall]?.();\n for (const event of queue) event.consumed();\n }\n}\n\n/**\n * Reduce the buffered `runProcess` events into a `CommandResult`, matching the\n * SSE-parsing logic the undici `run()` path used.\n */\nexport function assembleCommandResult(events: string[]): {\n exitCode: number;\n stdout: string;\n stderr: string;\n reason?: CommandExitReason;\n} {\n const stdoutLines: string[] = [];\n const stderrLines: string[] = [];\n let exitCode = -1;\n let reason: CommandExitReason | undefined;\n\n for (const eventJson of events) {\n const raw = JSON.parse(eventJson) as Record<string, unknown>;\n if (typeof raw.line === \"string\") {\n if (raw.stream === \"stderr\") {\n stderrLines.push(raw.line);\n } else {\n stdoutLines.push(raw.line);\n }\n } else if (\"exit_code\" in raw || \"signal\" in raw) {\n if (typeof raw.exit_code === \"number\") {\n exitCode = raw.exit_code;\n } else if (typeof raw.signal === \"number\") {\n exitCode = -raw.signal;\n } else {\n continue;\n }\n reason = exitReason(raw);\n }\n }\n\n return { exitCode, stdout: stdoutLines.join(\"\\n\"), stderr: stderrLines.join(\"\\n\"), reason };\n}\n\nconst KNOWN_EXIT_REASONS = new Set<string>(Object.values(CommandExitReason));\n\n/**\n * The daemon's reported exit reason. Sandboxes that predate the field, or a\n * reason this SDK does not know, fall back to one derived from how the process\n * ended; a timeout is only ever reported by the sandbox, never inferred.\n */\nfunction exitReason(raw: Record<string, unknown>): CommandExitReason {\n if (typeof raw.reason === \"string\" && KNOWN_EXIT_REASONS.has(raw.reason)) {\n return raw.reason as CommandExitReason;\n }\n if (raw.oom_killed === true) return CommandExitReason.OOM_KILLED;\n if (typeof raw.exit_code === \"number\") return CommandExitReason.EXITED;\n return CommandExitReason.SIGNALED;\n}\n","import { callNative, loadNativeSandboxBinding, nativeEventStream, type NativeEmit } from \"./native-sandbox.js\";\nimport { releaseNativeHandle } from \"./native-worker-client.js\";\nimport type { Traced } from \"./traced.js\";\n\nexport interface NativeCloudPart {\n name: string;\n data: Buffer;\n filename?: string;\n contentType?: string;\n}\n\nexport interface NativeCloudRequest {\n method: string;\n path: string;\n headersJson: string;\n body?: Buffer;\n parts?: NativeCloudPart[];\n statusOnlyCodes: number[];\n}\n\nexport interface NativeCloudResponse {\n status: number;\n headersJson: string;\n data: Uint8Array;\n traceId: string;\n}\n\nexport interface NativeCloudClient {\n request(request: NativeCloudRequest): Promise<NativeCloudResponse>;\n stream(request: NativeCloudRequest, emit: NativeEmit): Promise<string>;\n}\n\ninterface CloudTransportOptions {\n baseUrl: string;\n apiKey?: string;\n organizationId?: string;\n projectId?: string;\n userAgent: string;\n maxRetries: number;\n retryBackoffMs: number;\n timeoutMs: number;\n}\n\ninterface RequestOptions {\n body?: string | Blob | ArrayBuffer | Uint8Array | FormData;\n json?: unknown;\n headers?: Record<string, string>;\n /** Return these statuses without consuming their unused diagnostic bodies. */\n statusOnlyCodes?: Set<number>;\n}\n\n/** Only marshals values across the worker boundary; Rust owns all HTTP I/O. */\nexport class NativeCloudTransport {\n private native?: NativeCloudClient;\n private closed = false;\n\n constructor(private readonly options: CloudTransportOptions) {\n if (!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0 || options.maxRetries > 0xffff_ffff) {\n throw new RangeError(\"maxRetries must be a non-negative 32-bit integer\");\n }\n if (!Number.isFinite(options.retryBackoffMs) || options.retryBackoffMs < 0) {\n throw new RangeError(\"retryBackoffMs must be a non-negative finite number\");\n }\n }\n\n private client(): NativeCloudClient {\n if (this.closed) throw new Error(\"Tensorlake native client is closed\");\n if (this.native) return this.native;\n const ctor = loadNativeSandboxBinding().NativeCloudClient;\n if (!ctor) throw new Error(\"Native binding does not export NativeCloudClient; rebuild with 'npm run build:native'\");\n return this.native = new ctor(JSON.stringify(this.options));\n }\n\n close(): void {\n this.closed = true;\n releaseNativeHandle(this.native ?? null);\n this.native = undefined;\n }\n\n async requestResponse(method: string, path: string, options?: RequestOptions): Promise<Traced<Response>> {\n const request = await serializeRequest(method, path, options);\n const raw = await callNative(() => this.client().request(request));\n const response = new Response(\n [204, 205, 304].includes(raw.status) ? null : Uint8Array.from(raw.data).buffer,\n { status: raw.status, headers: JSON.parse(raw.headersJson) as Record<string, string> },\n );\n return Object.assign(response, { traceId: raw.traceId });\n }\n\n async requestJson<T>(method: string, path: string): Promise<Traced<T>> {\n const response = await this.requestResponse(method, path);\n const text = await response.text();\n const value = text ? JSON.parse(text) : null;\n return Object.assign(value ?? {}, { traceId: response.traceId }) as Traced<T>;\n }\n\n async *stream(method: string, path: string, signal?: AbortSignal): AsyncGenerator<Record<string, unknown>> {\n if (signal?.aborted) return;\n const request = await serializeRequest(method, path, { headers: { Accept: \"text/event-stream\" } });\n yield* nativeEventStream((emit) => this.client().stream(request, emit), undefined, signal);\n }\n}\n\nasync function serializeRequest(method: string, path: string, options?: RequestOptions): Promise<NativeCloudRequest> {\n const headers = { ...options?.headers };\n let body = options?.body;\n if (options?.json !== undefined) {\n body = JSON.stringify(options.json);\n if (!Object.keys(headers).some((key) => key.toLowerCase() === \"content-type\")) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n }\n const request: NativeCloudRequest = {\n method,\n path,\n headersJson: JSON.stringify(headers),\n statusOnlyCodes: [...(options?.statusOnlyCodes ?? [])],\n };\n if (body instanceof FormData) {\n request.parts = [];\n for (const [name, value] of body.entries()) {\n request.parts.push(typeof value === \"string\"\n ? { name, data: Buffer.from(value) }\n : { name, data: Buffer.from(await value.arrayBuffer()), filename: value.name, contentType: value.type || \"application/octet-stream\" });\n }\n } else if (body !== undefined) {\n if (body instanceof Blob) request.body = Buffer.from(await body.arrayBuffer());\n else if (typeof body === \"string\") request.body = Buffer.from(body);\n else if (body instanceof ArrayBuffer) request.body = Buffer.from(new Uint8Array(body));\n else request.body = Buffer.from(body);\n }\n return request;\n}\n","import { nanoid } from \"nanoid\";\n\nimport * as defaults from \"./defaults.js\";\nimport { NativeCloudTransport } from \"./native-cloud.js\";\nimport { fromSnakeKeys } from \"./models.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 transport: NativeCloudTransport;\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.transport = new NativeCloudTransport({\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 timeoutMs: defaults.DEFAULT_HTTP_TIMEOUT_MS,\n userAgent: `tensorlake-typescript-sdk/${defaults.SDK_VERSION}`,\n });\n }\n\n static forCloud(options?: CloudClientOptions): CloudClient {\n return new CloudClient(options);\n }\n\n close(): void {\n this.transport.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.transport.requestResponse(\"POST\", this.namespacePath(\"applications\"), {\n body: form,\n });\n }\n\n async deleteApplication(applicationName: string): Promise<void> {\n await this.transport.requestResponse(\n \"DELETE\",\n this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),\n );\n }\n\n async deleteSandboxImage(imageName: string): Promise<void> {\n await this.transport.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.transport.requestResponse(\n \"GET\",\n `${base}/by-name/${encodeURIComponent(imageName)}`,\n { statusOnlyCodes: 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.transport.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.transport.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.transport.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.transport.requestResponse(\"POST\", path, {\n body: new Uint8Array(),\n headers: { Accept: \"application/json\" },\n })\n : inputs.length === 1 && inputs[0].name === \"0\"\n ? await this.transport.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 = this.transport.stream(\n \"GET\",\n this.namespacePath(\n `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/progress`,\n ),\n );\n\n for await (const event of 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.transport.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.transport.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.transport.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.transport.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.transport.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.transport.requestResponse(\"POST\", base, {\n json: secret,\n headers: { \"Idempotency-Key\": nanoid() },\n statusOnlyCodes: new Set([409]),\n });\n if (response.status === 409) {\n const prefix = base.slice(0, -\"/secrets\".length);\n const existing = await this.transport.requestJson<{ id: string }>(\n \"GET\",\n `${prefix}/secret-names/${encodeURIComponent(secret.name)}`,\n );\n response = await this.transport.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.transport.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.transport.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.transport.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.transport.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.transport.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.transport.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 = this.transport.stream(\n \"GET\",\n `${trimTrailingSlashes(buildServicePath)}/builds/${encodeURIComponent(buildId)}/logs`,\n signal,\n );\n for await (const event of stream) {\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.transport.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.transport.requestResponse(\n \"GET\",\n this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),\n { statusOnlyCodes: 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\": \"@tensorlakeai/native-darwin-arm64\",\n \"linux-arm64\": \"@tensorlakeai/native-linux-arm64-gnu\",\n \"linux-arm64-musl\": \"@tensorlakeai/native-linux-arm64-musl\",\n \"linux-x64\": \"@tensorlakeai/native-linux-x64-gnu\",\n \"linux-x64-musl\": \"@tensorlakeai/native-linux-x64-musl\",\n \"win32-x64\": \"@tensorlakeai/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 @tensorlakeai/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 /**\n * Docker config JSON contents for this call, including credential helpers.\n * Omit to discover local Docker config at the start of the operation.\n * Pass \"{}\" to disable discovery and use no registry credentials.\n */\n dockerConfigJson?: string;\n\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 * Docker config JSON contents for this call, including credential helpers.\n * Omit to discover local Docker config at the start of the operation.\n * Pass \"{}\" to disable discovery and use no registry credentials.\n */\n dockerConfigJson?: string;\n\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 dockerConfigJson?: string | 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 loadDockerConfigJson(): string;\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 dockerConfigJson: options.dockerConfigJson,\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 dockerConfigJson: options.dockerConfigJson,\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 MiB] [--disk_mb MiB] [--builder_disk_mb MiB] [--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 const dockerConfigJson = loadNativeBinding().loadDockerConfigJson();\n await createSandboxImage(\n dockerfilePath,\n {\n registeredName: parsed.values.name,\n dockerConfigJson,\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 MiB] [--disk_mb MiB] [--builder_disk_mb MiB] [--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 const dockerConfigJson = loadNativeBinding().loadDockerConfigJson();\n await importSandboxImage(\n imageReference,\n {\n registeredName: parsed.values.name,\n dockerConfigJson,\n cpus,\n memoryMb,\n diskMb,\n builderDiskMb,\n dockerCompat: parsed.values.docker_compat,\n isPublic: parsed.values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IAAI,MAAM,yBAAyB,OAAO,OAAO,IAAI,EAAE;AAAA,EAC/D;AACA,MAAI,YAAY,QAAQ,CAAC,OAAO,UAAU,QAAQ,GAAG;AACnD,UAAM,IAAI,MAAM,2BAA2B,OAAO,OAAO,MAAM,EAAE;AAAA,EACnE;AACA,MAAI,UAAU,QAAQ,CAAC,OAAO,UAAU,MAAM,GAAG;AAC/C,UAAM,IAAI,MAAM,4BAA4B,OAAO,OAAO,OAAO,EAAE;AAAA,EACrE;AACA,MAAI,iBAAiB,QAAQ,CAAC,OAAO,UAAU,aAAa,GAAG;AAC7D,UAAM,IAAI;AAAA,MACR,oCAAoC,OAAO,OAAO,eAAe;AAAA,IACnE;AAAA,EACF;AAEA,QAAM,mBAAmB,kBAAkB,EAAE,qBAAqB;AAClE,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,MACE,gBAAgB,OAAO,OAAO;AAAA,MAC9B;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,cAAc,OAAO,OAAO;AAAA,MAC5B,UAAU,OAAO,OAAO;AAAA,IAC1B;AAAA,IACA,EAAE,MAAM,kBAAkB,WAAW,KAAK;AAAA,EAC5C;AACF;AA3xBA,IAkJI,qBACA,0BAqDEA;AAxMN;AAAA;AAAA;AAIA;AAEA;AAEA;AAgMA,IAAMA,sBAAqB;AAAA;AAAA;","names":["CommandExitReason","path","trimTrailingSlashes","path","createSandboxImage","detectLinuxLibc","fs","read","count","createRequire","path","fileURLToPath","require","path","existsSync","DEFAULT_IMAGE_NAME"]}
1
+ {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/image.ts","../lib/libc.cjs","../src/native-binding.ts","../src/enum.ts","../src/image-builds.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","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\": \"@tensorlakeai/native-darwin-arm64\",\n \"linux-arm64\": \"@tensorlakeai/native-linux-arm64-gnu\",\n \"linux-arm64-musl\": \"@tensorlakeai/native-linux-arm64-musl\",\n \"linux-x64\": \"@tensorlakeai/native-linux-x64-gnu\",\n \"linux-x64-musl\": \"@tensorlakeai/native-linux-x64-musl\",\n \"win32-x64\": \"@tensorlakeai/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 @tensorlakeai/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","/** Decode a response enum while accepting values from newer servers. */\nexport function enumValue<E extends Record<string, string> & { UNKNOWN: string }>(\n values: E,\n value: unknown,\n): E[keyof E] {\n return typeof value === \"string\" && Object.values(values).includes(value)\n ? value as E[keyof E]\n : values.UNKNOWN as E[keyof E];\n}\n\n/** Diagnostic data is deliberately invisible to equality and JSON serialization. */\nexport function withRaw<T extends object>(value: T, raw: Record<string, unknown>): T & { readonly raw: Record<string, unknown> } {\n return Object.defineProperty(value, \"raw\", { value: raw, enumerable: false, configurable: true }) as T & { readonly raw: Record<string, unknown> };\n}\n","import path from \"node:path\";\nimport { enumValue, withRaw } from \"./enum.js\";\nimport os from \"node:os\";\nimport { existsSync, mkdtempSync, rmSync } from \"node:fs\";\nimport type { SandboxTemplate } from \"./cloud-models.js\";\nimport { Image, dockerfileContent } from \"./image.js\";\nimport {\n __imageBuildInternals,\n type CreateSandboxImageDeps,\n} from \"./sandbox-image.js\";\n\n/**\n * Image Service build operations for CAS sandbox images.\n *\n * A CAS (content-addressed streaming) image is built or imported by an Image\n * Service *build operation*. This module exposes that operation directly:\n * {@link startImageBuild} / {@link startImageImport} admit a build (and upload\n * and seal its context) and return an {@link ImageBuildHandle} without\n * waiting; {@link getImageBuild} looks a build up by id; the handle's\n * `refresh`, `wait` and `cancel` read, wait for and cancel it.\n *\n * **CAS only.** Everything here addresses the Image Service. Legacy images\n * (`createSandboxImage` without `cas`, `sandbox_template_` ids, `.tlsnap`\n * snapshots) have no build operation: a `sandbox_template_` or `image_`\n * reference passed as a build id is refused locally, before any request, and\n * the legacy functions in `sandbox-image.ts` keep their own requests,\n * results, errors and interruption behavior.\n *\n * Response enum fields map unfamiliar wire values to `UNKNOWN`. `raw` is\n * diagnostic only and excluded from equality, hashing, and SDK serialization\n * (`JSON.stringify`). Events retain their original wire strings.\n *\n * **Build ids are the immutable record.** An image name and its `image_` id\n * name the *current* image; a rebuild replaces what they point at. A build id\n * and its result never change, so `wait` returns this build's own result even\n * after the image was rebuilt or deleted.\n *\n * **Cancellation by build id is sufficient.** Admission returns it, the CLI\n * prints it, and the `image_build_in_progress` conflict names it as\n * `activeBuildId`. The client request id (the admission's `Idempotency-Key`)\n * is kept on the handle only as a recovery aid for a lost admission answer.\n *\n * **AbortSignal versus timeout.** An `AbortSignal` passed to the new APIs (and\n * to `createSandboxImage`/`importSandboxImage` with `cas: true`) *requests\n * remote cancellation*: the Rust core runs a bounded (30 s) handshake and the\n * promise rejects with {@link ImageBuildInterruptedError} carrying the\n * outcome. A wait `timeoutMs` merely stops waiting: it rejects with\n * {@link ImageBuildTimeoutError} and leaves the build running. Abandoning a\n * promise, losing the process or dropping a handle never cancels the build.\n */\n\nexport enum ImageBuildStatus {\n PENDING = \"pending\",\n RUNNING = \"running\",\n SUCCEEDED = \"succeeded\",\n FAILED = \"failed\",\n CANCELLED = \"cancelled\",\n UNKNOWN = \"unknown\",\n}\n\nexport enum ImageBuildPhase {\n AWAITING_CONTEXT = \"awaiting_context\",\n STARTING_BUILDER = \"starting_builder\",\n EXECUTING = \"executing\",\n SNAPSHOTTING = \"snapshotting\",\n PUBLISHING = \"publishing\",\n FINISHED = \"finished\",\n UNKNOWN = \"unknown\",\n}\n\nexport enum ImageBuildKind {\n DOCKERFILE = \"dockerfile\",\n IMPORT = \"import\",\n DIRECT = \"direct\",\n UNKNOWN = \"unknown\",\n}\n\nexport enum ImageBuildCancellationOutcome {\n CANCELLED = \"cancelled\",\n ALREADY_CANCELLED = \"already_cancelled\",\n ALREADY_COMPLETED = \"already_completed\",\n ALREADY_FAILED = \"already_failed\",\n NOT_ADMITTED = \"not_admitted\",\n UNCONFIRMED = \"unconfirmed\",\n UNKNOWN = \"unknown\",\n}\n\nfunction isConfirmedCancellation(outcome: ImageBuildCancellationOutcome | null | undefined): boolean {\n return outcome === ImageBuildCancellationOutcome.CANCELLED ||\n outcome === ImageBuildCancellationOutcome.ALREADY_CANCELLED ||\n outcome === ImageBuildCancellationOutcome.ALREADY_FAILED;\n}\n\nexport enum ImageBuildErrorCode {\n USAGE = \"usage\",\n AUTH = \"auth\",\n NOT_FOUND = \"not_found\",\n IMAGE_BUILD_IN_PROGRESS = \"image_build_in_progress\",\n CLIENT_REQUEST_ID_MISMATCH = \"client_request_id_mismatch\",\n FAILED = \"failed\",\n CANCELLED = \"cancelled\",\n TIMEOUT = \"timeout\",\n INTERRUPTED = \"interrupted\",\n SERVICE = \"service\",\n INTERNAL = \"internal\",\n UNKNOWN = \"unknown\",\n}\n\n// --- Errors ------------------------------------------------------------------\n\n/** Structured payload the native binding attaches to image-build failures. */\nexport interface ImageBuildErrorDetails {\n code: ImageBuildErrorCode;\n message: string;\n buildId?: string | null;\n clientRequestId?: string | null;\n imageName?: string | null;\n activeBuildId?: string | null;\n activeKind?: ImageBuildKind | null;\n activeStatus?: ImageBuildStatus | null;\n error?: string | null;\n info?: ImageBuildInfo | null;\n outcome?: ImageBuildCancellationOutcome | null;\n confirmed?: boolean | null;\n result?: Record<string, unknown> | null;\n waitedSecs?: number | null;\n status?: number | null;\n}\n\n/** An Image Service build operation failed. `code` is stable. */\nexport class ImageBuildError extends Error {\n readonly code: ImageBuildErrorCode;\n readonly buildId?: string;\n readonly clientRequestId?: string;\n readonly details: ImageBuildErrorDetails;\n declare readonly raw: Readonly<Record<string, unknown>>;\n\n constructor(details: ImageBuildErrorDetails) {\n super(details.message);\n this.name = \"ImageBuildError\";\n this.code = details.code;\n this.details = { ...details };\n withRaw(this, {});\n if (\"confirmed\" in details) {\n this.details.confirmed = details.confirmed === true && isConfirmedCancellation(details.outcome);\n }\n if (details.buildId) this.buildId = details.buildId;\n if (details.clientRequestId) this.clientRequestId = details.clientRequestId;\n }\n}\n\n/**\n * No such build is visible to the project: unknown, foreign or retired. A\n * finished build is kept only while it is its image's current build; a later\n * build of the image or deleting the image retires it.\n */\nexport class ImageBuildNotFoundError extends ImageBuildError {\n constructor(details: ImageBuildErrorDetails) {\n super(details);\n this.name = \"ImageBuildNotFoundError\";\n }\n}\n\n/**\n * The image name already has an unfinished build or import. Cancel\n * `activeBuildId` before starting another; the SDK never does so itself.\n */\nexport class ImageBuildInProgressError extends ImageBuildError {\n readonly imageName?: string;\n readonly activeBuildId?: string;\n readonly activeKind?: ImageBuildKind;\n readonly activeStatus?: ImageBuildStatus;\n\n constructor(details: ImageBuildErrorDetails) {\n super(details);\n this.name = \"ImageBuildInProgressError\";\n if (details.imageName) this.imageName = details.imageName;\n if (details.activeBuildId) this.activeBuildId = details.activeBuildId;\n if (details.activeKind) this.activeKind = details.activeKind;\n if (details.activeStatus) this.activeStatus = details.activeStatus;\n }\n}\n\n/** The service reports the build failed; `error` is its message. */\nexport class ImageBuildFailedError extends ImageBuildError {\n readonly error: string;\n readonly info?: ImageBuildInfo;\n\n constructor(details: ImageBuildErrorDetails) {\n super(details);\n this.name = \"ImageBuildFailedError\";\n this.error = details.error ?? \"no error recorded\";\n if (details.info) this.info = details.info;\n }\n}\n\n/** The service reports the build was cancelled (a distinct outcome). */\nexport class ImageBuildCancelledError extends ImageBuildError {\n readonly info?: ImageBuildInfo;\n\n constructor(details: ImageBuildErrorDetails) {\n super(details);\n this.name = \"ImageBuildCancelledError\";\n if (details.info) this.info = details.info;\n }\n}\n\n/** The caller stopped waiting. The build may still be running. */\nexport class ImageBuildTimeoutError extends ImageBuildError {\n constructor(details: ImageBuildErrorDetails) {\n super(details);\n this.name = \"ImageBuildTimeoutError\";\n }\n}\n\n/**\n * An `AbortSignal` ran the cancellation handshake. `outcome` is `cancelled`,\n * `already_completed`, `already_cancelled`, `already_failed`, `not_admitted`\n * or `unconfirmed`; `confirmed` is true only when the remote build is known\n * not to publish. `not_admitted` is an observation, not a cancellation.\n */\nexport class ImageBuildInterruptedError extends ImageBuildError {\n readonly outcome: ImageBuildCancellationOutcome;\n readonly confirmed: boolean;\n readonly result?: Record<string, unknown>;\n\n constructor(details: ImageBuildErrorDetails) {\n super(details);\n this.name = \"ImageBuildInterruptedError\";\n this.outcome = details.outcome ?? ImageBuildCancellationOutcome.UNCONFIRMED;\n this.confirmed = this.details.confirmed === true;\n if (details.result) this.result = details.result;\n }\n}\n\nfunction camelize(key: string): string {\n return key.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\n/**\n * Translate a native `{category: \"image_build\", ...}` rejection into the\n * typed error classes. Other errors pass through unchanged.\n */\nexport function toImageBuildError(error: unknown): unknown {\n if (!(error instanceof Error)) return error;\n let payload: Record<string, unknown>;\n try {\n payload = JSON.parse(error.message) as Record<string, unknown>;\n } catch {\n return error;\n }\n if (!payload || payload.category !== \"image_build\") return error;\n const details: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(payload)) {\n if (key === \"category\") continue;\n details[camelize(key)] = value;\n }\n details.code = enumValue(ImageBuildErrorCode, details.code || ImageBuildErrorCode.INTERNAL);\n if (\"activeKind\" in details) details.activeKind = details.activeKind ? enumValue(ImageBuildKind, details.activeKind) : null;\n if (\"activeStatus\" in details) details.activeStatus = details.activeStatus ? enumValue(ImageBuildStatus, details.activeStatus) : null;\n if (\"outcome\" in details) details.outcome = details.outcome ? enumValue(ImageBuildCancellationOutcome, details.outcome) : null;\n if (\"info\" in details) details.info = buildInfoOrNull(details.info);\n const typed = details as unknown as ImageBuildErrorDetails;\n const errors = {\n not_found: ImageBuildNotFoundError, image_build_in_progress: ImageBuildInProgressError,\n failed: ImageBuildFailedError, cancelled: ImageBuildCancelledError,\n timeout: ImageBuildTimeoutError, interrupted: ImageBuildInterruptedError,\n };\n const ErrorClass = errors[typed.code as keyof typeof errors] ?? ImageBuildError;\n return withRaw(new ErrorClass(typed), payload);\n}\n\n// --- Models ------------------------------------------------------------------\n\n/**\n * The published image of a succeeded build, in the sandbox-template shape\n * the merged catalog answers (derived by the core from the Image Service's\n * trimmed record): one image representation for `findSandboxImageByName`,\n * `listSandboxImages` and build results.\n */\nexport type ImageBuildResult = SandboxTemplate;\n\n/**\n * One build or import as the Image Service reports it (the twelve-field\n * `BuildInfo`; the service exposes no cleanup state, phase deadline,\n * content digest or upload capability on a build).\n */\nexport interface ImageBuildInfo {\n buildId: string;\n clientRequestId?: string | null;\n kind?: ImageBuildKind | null;\n name?: string | null;\n status: ImageBuildStatus;\n phase?: ImageBuildPhase | null;\n attemptNo: number;\n builderSandboxId?: string | null;\n error?: string | null;\n result?: ImageBuildResult | null;\n operationDeadlineMs?: number | null;\n createdAtMs?: number | null;\n updatedAtMs?: number | null;\n /** The service record as received, snake_case, with unknown fields. */\n raw: Record<string, unknown>;\n}\n\n/**\n * The service's answer to a cancellation. `outcome` is `cancelled`\n * (durable), `already_cancelled`, `already_completed` (publication won),\n * `already_failed` or `not_admitted` (nothing indexed under the client\n * request id: not a cancellation and no promise about a delayed admission).\n */\nexport interface CancelImageBuildOutcome {\n outcome: ImageBuildCancellationOutcome;\n build: ImageBuildInfo | null;\n /** Whether the build is known not to publish. */\n confirmed: boolean;\n raw: Record<string, unknown>;\n}\n\nfunction camelizeRecord(value: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value)) out[camelize(key)] = inner;\n return out;\n}\n\nfunction buildInfoOrNull(value: unknown): ImageBuildInfo | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n try { return parseBuildInfo(value); } catch (error) {\n if (error instanceof ImageBuildError) return null;\n throw error;\n }\n}\n\nfunction decodeResponse(value: unknown): Record<string, unknown> {\n try {\n const raw = typeof value === \"string\" ? JSON.parse(value) : value;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) throw new TypeError(\"expected a response object\");\n return raw as Record<string, unknown>;\n } catch (error) {\n throw withRaw(new ImageBuildError({ code: ImageBuildErrorCode.SERVICE, message: `Invalid image-build response: ${String(error)}` }), { response: value });\n }\n}\n\nfunction parseBuildInfo(value: unknown): ImageBuildInfo {\n const raw = decodeResponse(value);\n if (raw.status == null) {\n throw withRaw(new ImageBuildError({ code: ImageBuildErrorCode.SERVICE, message: \"Invalid image-build response: missing status\" }), { response: value });\n }\n const attempt = raw.attempt_no ?? 0;\n const attemptNo = Number(attempt);\n if ((typeof attempt !== \"number\" && typeof attempt !== \"string\") ||\n (typeof attempt === \"string\" && attempt.trim() === \"\") ||\n !Number.isSafeInteger(attemptNo)) {\n throw withRaw(new ImageBuildError({ code: ImageBuildErrorCode.SERVICE, message: \"Invalid image-build attempt_no\" }), { response: value });\n }\n const camel = camelizeRecord(raw);\n const result = raw.result && typeof raw.result === \"object\"\n ? camelizeRecord(raw.result as Record<string, unknown>) as unknown as ImageBuildResult : null;\n return withRaw({\n buildId: String(raw.build_id ?? \"\"),\n clientRequestId: (camel.clientRequestId as string | null | undefined) ?? null,\n kind: raw.kind ? enumValue(ImageBuildKind, raw.kind) : null,\n name: (raw.name as string | null | undefined) ?? null,\n status: enumValue(ImageBuildStatus, raw.status),\n phase: raw.phase ? enumValue(ImageBuildPhase, raw.phase) : null,\n attemptNo,\n builderSandboxId: (camel.builderSandboxId as string | null | undefined) ?? null,\n error: (raw.error as string | null | undefined) ?? null,\n result,\n operationDeadlineMs: (camel.operationDeadlineMs as number | null | undefined) ?? null,\n createdAtMs: (camel.createdAtMs as number | null | undefined) ?? null,\n updatedAtMs: (camel.updatedAtMs as number | null | undefined) ?? null,\n }, raw);\n}\n\nfunction parseResult(json: string): ImageBuildResult {\n return camelizeRecord(decodeResponse(json)) as unknown as ImageBuildResult;\n}\n\n// --- Native plumbing -----------------------------------------------------------\n\nexport interface ImageBuildEvent {\n type: string;\n message?: string;\n stream?: string;\n build_id?: string;\n client_request_id?: string | null;\n status?: string;\n phase?: string | null;\n attempt?: number;\n outcome?: string;\n confirmed?: boolean;\n [key: string]: unknown;\n}\n\nexport interface ImageBuildWaitOptions {\n /**\n * Caller bound in milliseconds on top of the service-informed deadline.\n * Expiry rejects with {@link ImageBuildTimeoutError} and leaves the build\n * running; it does not cancel.\n */\n timeoutMs?: number;\n /** Stream `tl-image-builder` output as `build_log` events. */\n followLogs?: boolean;\n /** Requests remote cancellation (bounded handshake), unlike `timeoutMs`. */\n signal?: AbortSignal;\n /**\n * Event callback. A throwing callback is recorded and rethrown once the\n * native call returns; it does not cancel the build.\n */\n emit?: (event: ImageBuildEvent) => void;\n verbose?: boolean;\n}\n\ninterface Credentials {\n apiUrl: string;\n bearerToken: string;\n namespace: string;\n}\n\nfunction credentialsFromEnv(): Credentials {\n const context = __imageBuildInternals.buildContextFromEnv();\n if (!context.apiKey) {\n if (context.personalAccessToken) {\n throw new ImageBuildError({\n code: ImageBuildErrorCode.AUTH,\n message:\n \"Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only.\",\n });\n }\n throw new ImageBuildError({ code: ImageBuildErrorCode.AUTH, message: \"Missing TENSORLAKE_API_KEY credentials.\" });\n }\n return { apiUrl: context.apiUrl, bearerToken: context.apiKey, namespace: context.namespace };\n}\n\nfunction clientOptions(credentials: Credentials) {\n return {\n apiUrl: credentials.apiUrl,\n bearerToken: credentials.bearerToken,\n namespace: credentials.namespace,\n useScopeHeaders: false,\n };\n}\n\n/**\n * New operations never reinterpret legacy references: fail before any\n * request so no Image Service or platform call is made.\n */\nfunction rejectLegacyReference(buildId: string): void {\n if (typeof buildId !== \"string\" || buildId.trim().length === 0) {\n throw new ImageBuildError({ code: ImageBuildErrorCode.USAGE, message: \"buildId must be a non-empty string\" });\n }\n if (buildId.startsWith(\"sandbox_template_\")) {\n throw new ImageBuildError({\n code: ImageBuildErrorCode.USAGE,\n message: `'${buildId}' is a legacy sandbox template id; legacy images have no build operation to get, wait for or cancel`,\n buildId,\n });\n }\n if (buildId.startsWith(\"image_\")) {\n throw new ImageBuildError({\n code: ImageBuildErrorCode.USAGE,\n message: `'${buildId}' is an image id, not a build id; look the image up with findSandboxImageByName or use the build id admission returned`,\n buildId,\n });\n }\n}\n\n/**\n * Run a native CAS operation with an optional AbortSignal wired to the Rust\n * interrupt registry. Only the new operation API and explicitly selected CAS\n * paths call this; legacy calls never reach it.\n */\nexport async function __runWithInterrupt<T>(\n signal: AbortSignal | undefined,\n run: (interruptId: number | undefined) => Promise<T>,\n): Promise<T> {\n const binding = __imageBuildInternals.loadNativeBinding();\n if (signal === undefined) {\n try {\n return await run(undefined);\n } catch (error) {\n throw toImageBuildError(error);\n }\n }\n const interruptId = binding.createImageBuildInterrupt();\n const onAbort = () => binding.triggerImageBuildInterrupt(interruptId);\n if (signal.aborted) onAbort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n return await run(interruptId);\n } catch (error) {\n throw toImageBuildError(error);\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n binding.releaseImageBuildInterrupt(interruptId);\n }\n}\n\nfunction makeEmitter(options: { emit?: (event: ImageBuildEvent) => void; verbose?: boolean }) {\n const emit =\n options.emit ??\n (options.verbose ? __imageBuildInternals.stderrEmit : __imageBuildInternals.noopEmit);\n let emitError: unknown;\n const forward = (event: {\n eventType: string;\n stream?: string | null;\n message: string;\n buildId?: string | null;\n clientRequestId?: string | null;\n status?: string | null;\n phase?: string | null;\n attempt?: number | null;\n outcome?: string | null;\n confirmed?: boolean | null;\n }) => {\n try {\n emit(__imageBuildInternals.eventToEmitDict(event) as ImageBuildEvent);\n } catch (error) {\n emitError ??= error;\n }\n };\n return {\n forward,\n emit,\n rethrow() {\n if (emitError != null) throw emitError;\n },\n };\n}\n\n// --- Handle --------------------------------------------------------------------\n\n/**\n * One admitted CAS build. Holds the build identity and the caller's\n * credentials; creating or dropping it performs no network I/O.\n */\nexport class ImageBuildHandle {\n readonly buildId: string;\n /**\n * The admission's request id, when this handle started the build. Never\n * needed to cancel; a recovery aid for a lost admission answer.\n */\n readonly clientRequestId: string | null;\n #info: ImageBuildInfo;\n #credentials: Credentials;\n\n /** @internal */\n constructor(info: ImageBuildInfo, credentials: Credentials, clientRequestId?: string | null) {\n this.buildId = info.buildId;\n this.clientRequestId = clientRequestId ?? info.clientRequestId ?? null;\n this.#info = info;\n this.#credentials = credentials;\n }\n\n /** The last observed state. */\n get info(): ImageBuildInfo {\n return this.#info;\n }\n\n /** Re-read the current state. */\n async refresh(): Promise<ImageBuildInfo> {\n const binding = __imageBuildInternals.loadNativeBinding();\n let json: string;\n try {\n json = await binding.getImageBuild(clientOptions(this.#credentials), this.buildId);\n } catch (error) {\n throw toImageBuildError(error);\n }\n this.#info = parseBuildInfo(json);\n return this.#info;\n }\n\n /**\n * Wait for publication and return this build's immutable result. See\n * {@link ImageBuildWaitOptions} for the timeout/abort distinction.\n */\n async wait(options: ImageBuildWaitOptions = {}): Promise<ImageBuildResult> {\n const binding = __imageBuildInternals.loadNativeBinding();\n const emitter = makeEmitter(options);\n const json = await __runWithInterrupt(options.signal, (interruptId) =>\n binding.waitImageBuild(\n clientOptions(this.#credentials),\n this.buildId,\n { timeoutMs: options.timeoutMs, followLogs: options.followLogs ?? false },\n emitter.forward,\n interruptId,\n ),\n );\n emitter.rethrow();\n const raw = decodeResponse(json);\n const result = camelizeRecord(raw) as unknown as ImageBuildResult;\n this.#info = withRaw({ ...this.#info, status: ImageBuildStatus.SUCCEEDED, result },\n { ...this.#info.raw, status: \"succeeded\", result: raw });\n return result;\n }\n\n /** Cancel this build by its id (the sufficient selector). */\n async cancel(): Promise<CancelImageBuildOutcome> {\n return cancelImageBuildWith(this.#credentials, { buildId: this.buildId });\n }\n}\n\n// --- Operations ------------------------------------------------------------------\n\nexport interface StartImageBuildOptions {\n registeredName?: string;\n cpus?: number;\n memoryMb?: number;\n diskMb?: number;\n isPublic?: boolean;\n contextDir?: string;\n buildArgs?: Record<string, string>;\n dockerConfigJson?: string;\n /** Requests remote cancellation of the admission/upload in progress. */\n signal?: AbortSignal;\n emit?: (event: ImageBuildEvent) => void;\n verbose?: boolean;\n}\n\nexport interface StartImageImportOptions {\n registeredName?: string;\n cpus?: number;\n memoryMb?: number;\n diskMb?: number;\n isPublic?: boolean;\n dockerConfigJson?: string;\n signal?: AbortSignal;\n emit?: (event: ImageBuildEvent) => void;\n verbose?: boolean;\n}\n\nfunction decodeStarted(json: string, credentials: Credentials): ImageBuildHandle {\n const payload = decodeResponse(json);\n const build = payload.build as Record<string, unknown> | null | undefined;\n if (!build || typeof build !== \"object\" || Array.isArray(build) ||\n typeof build.build_id !== \"string\" || !build.build_id.trim()) {\n throw withRaw(new ImageBuildError({\n code: ImageBuildErrorCode.SERVICE,\n message: \"Invalid image-build admission: expected a build with a non-empty build_id\",\n }), { response: payload });\n }\n return new ImageBuildHandle(parseBuildInfo(build), credentials, payload.client_request_id as string | null | undefined);\n}\n\n/**\n * Admit a CAS image build and return without waiting. Parses the source like\n * `createSandboxImage` with `cas: true`, admits under a fresh client request\n * id, uploads and seals the context, and returns a handle whose `wait`\n * finishes the operation. The build keeps running if this process exits.\n */\nexport async function startImageBuild(\n source: string | Image,\n options: StartImageBuildOptions = {},\n deps: CreateSandboxImageDeps = {},\n): Promise<ImageBuildHandle> {\n const emitter = makeEmitter({ emit: deps.emit ?? options.emit, verbose: options.verbose });\n let dockerfilePath: string;\n let dockerfileText: string | undefined;\n let contextDir: string | undefined;\n let name: string;\n let tempContextDir: string | undefined;\n if (source instanceof Image) {\n if (!source.baseImage) throw new Error(\"Image must have a baseImage to build\");\n if (options.contextDir != null) {\n contextDir = path.resolve(options.contextDir);\n } else if (__imageBuildInternals.imageRequiresContext(source)) {\n throw new Error(\n \"This image reads files from the host (via COPY/ADD or a RUN bind mount), so it needs a \" +\n \"build context. Pass `contextDir` pointing at the directory that contains those \" +\n \"sources; they resolve relative to it, like `docker build <contextDir>`.\",\n );\n } else {\n tempContextDir = mkdtempSync(path.join(os.tmpdir(), \"tl-build-context-\"));\n contextDir = tempContextDir;\n }\n dockerfilePath = path.join(contextDir, \"Dockerfile\");\n let text = dockerfileContent(source);\n if (!text.endsWith(\"\\n\")) text += \"\\n\";\n dockerfileText = text;\n name = options.registeredName ?? source.name;\n } else if (typeof source === \"string\") {\n const resolved = path.resolve(source);\n if (!existsSync(resolved)) throw new Error(`Dockerfile not found: ${source}`);\n dockerfilePath = resolved;\n name = options.registeredName ?? __imageBuildInternals.defaultRegisteredName(resolved);\n } else {\n throw new TypeError(`source must be an Image or a Dockerfile path, got ${typeof source}`);\n }\n try {\n const credentials = credentialsFromEnv();\n const binding = __imageBuildInternals.loadNativeBinding();\n emitter.emit({ type: \"status\", message: `Building image '${name}'...` });\n const json = await __runWithInterrupt(options.signal, (interruptId) =>\n binding.startImageBuild(\n {\n apiUrl: credentials.apiUrl,\n bearerToken: credentials.bearerToken,\n dockerfilePath,\n registeredName: name,\n diskMb: options.diskMb,\n cpus: options.cpus,\n memoryMb: options.memoryMb,\n isPublic: options.isPublic ?? false,\n namespace: credentials.namespace,\n useScopeHeaders: false,\n dockerConfigJson: options.dockerConfigJson,\n dockerfileText,\n contextDir,\n cas: true,\n buildArgs: options.buildArgs,\n },\n emitter.forward,\n interruptId,\n ),\n );\n emitter.rethrow();\n return decodeStarted(json, credentials);\n } finally {\n if (tempContextDir != null) rmSync(tempContextDir, { recursive: true, force: true });\n }\n}\n\n/** Admit a CAS registry import and return without waiting. */\nexport async function startImageImport(\n imageReference: string,\n options: StartImageImportOptions = {},\n deps: CreateSandboxImageDeps = {},\n): Promise<ImageBuildHandle> {\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 const name =\n options.registeredName ?? __imageBuildInternals.defaultRegisteredNameFromImage(reference);\n const emitter = makeEmitter({ emit: deps.emit ?? options.emit, verbose: options.verbose });\n const credentials = credentialsFromEnv();\n const binding = __imageBuildInternals.loadNativeBinding();\n emitter.emit({ type: \"status\", message: `Importing image '${reference}' as '${name}'...` });\n const json = await __runWithInterrupt(options.signal, (interruptId) =>\n binding.startImageImport(\n {\n apiUrl: credentials.apiUrl,\n bearerToken: credentials.bearerToken,\n imageReference: reference,\n registeredName: name,\n diskMb: options.diskMb,\n cpus: options.cpus,\n memoryMb: options.memoryMb,\n isPublic: options.isPublic ?? false,\n namespace: credentials.namespace,\n useScopeHeaders: false,\n dockerConfigJson: options.dockerConfigJson,\n cas: true,\n },\n emitter.forward,\n interruptId,\n ),\n );\n emitter.rethrow();\n return decodeStarted(json, credentials);\n}\n\n/**\n * Look a build up by its service-generated id. Unknown and foreign builds\n * reject with {@link ImageBuildNotFoundError}; a legacy `sandbox_template_`\n * or an `image_` reference is refused before any request.\n */\nexport async function getImageBuild(buildId: string): Promise<ImageBuildHandle> {\n rejectLegacyReference(buildId);\n const credentials = credentialsFromEnv();\n const binding = __imageBuildInternals.loadNativeBinding();\n let json: string;\n try {\n json = await binding.getImageBuild(clientOptions(credentials), buildId);\n } catch (error) {\n throw toImageBuildError(error);\n }\n return new ImageBuildHandle(parseBuildInfo(json), credentials);\n}\n\n/**\n * `getImageBuild(buildId)` then `wait(options)`, as one interruptible\n * operation: the lookup runs inside the native wait, under the same\n * `AbortSignal` and `timeoutMs`, so an abort during a slow or stalled first\n * request still cancels the build by its id.\n */\nexport async function waitImageBuild(\n buildId: string,\n options: ImageBuildWaitOptions = {},\n): Promise<ImageBuildResult> {\n rejectLegacyReference(buildId);\n const credentials = credentialsFromEnv();\n const binding = __imageBuildInternals.loadNativeBinding();\n const emitter = makeEmitter(options);\n const json = await __runWithInterrupt(options.signal, (interruptId) =>\n binding.waitImageBuild(\n clientOptions(credentials),\n buildId,\n { timeoutMs: options.timeoutMs, followLogs: options.followLogs ?? false },\n emitter.forward,\n interruptId,\n ),\n );\n emitter.rethrow();\n return parseResult(json);\n}\n\nexport interface CancelImageBuildSelector {\n /** The sufficient, documented selector. */\n buildId?: string;\n /**\n * Only to recover an admission whose response was lost. Its `not_admitted`\n * outcome is an observation of absence, not a cancellation, and does not\n * prevent a delayed admission (cancel again by request id then).\n */\n clientRequestId?: string;\n}\n\nasync function cancelImageBuildWith(\n credentials: Credentials,\n selector: CancelImageBuildSelector,\n): Promise<CancelImageBuildOutcome> {\n const binding = __imageBuildInternals.loadNativeBinding();\n let json: string;\n try {\n json = await binding.cancelImageBuild(clientOptions(credentials), {\n buildId: selector.buildId,\n clientRequestId: selector.clientRequestId,\n });\n } catch (error) {\n throw toImageBuildError(error);\n }\n const payload = decodeResponse(json);\n const outcome = enumValue(ImageBuildCancellationOutcome, payload.outcome);\n return withRaw({ outcome, build: buildInfoOrNull(payload.build), confirmed: isConfirmedCancellation(outcome) }, payload);\n}\n\n/** Cancel a build. Exactly one selector; the build id alone is sufficient. */\nexport async function cancelImageBuild(\n selector: CancelImageBuildSelector,\n): Promise<CancelImageBuildOutcome> {\n const hasBuild = selector.buildId != null;\n const hasRequest = selector.clientRequestId != null;\n if (hasBuild === hasRequest) {\n throw new ImageBuildError({\n code: ImageBuildErrorCode.USAGE,\n message: \"pass exactly one of buildId or clientRequestId\",\n });\n }\n if (selector.buildId != null) rejectLegacyReference(selector.buildId);\n return cancelImageBuildWith(credentialsFromEnv(), selector);\n}\n\nexport type { SandboxTemplate };\n","import path from \"node:path\";\nimport os from \"node:os\";\nimport { existsSync, mkdtempSync, rmSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\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\";\nimport { __runWithInterrupt } from \"./image-builds.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 /**\n * Docker config JSON contents for this call, including credential helpers.\n * Omit to discover local Docker config at the start of the operation.\n * Pass \"{}\" to disable discovery and use no registry credentials.\n */\n dockerConfigJson?: string;\n\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 * Build a CAS (content-addressed streaming) image through the Image\n * Service instead of a legacy template. Off by default.\n */\n cas?: boolean;\n /**\n * Dockerfile build args (`--build-arg KEY=VALUE`), forwarded to BuildKit\n * and expanded in `FROM` references. CAS builds only; a legacy build with\n * build args is rejected.\n */\n buildArgs?: Record<string, string>;\n /**\n * CAS builds only (`cas: true`): aborting requests *remote cancellation*\n * of the Image Service build through a bounded handshake, and the call\n * rejects with `ImageBuildInterruptedError` carrying the outcome. It is\n * rejected for legacy builds, which have no build operation to cancel.\n * Abandoning the promise alone never cancels anything.\n */\n signal?: AbortSignal;\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 * Docker config JSON contents for this call, including credential helpers.\n * Omit to discover local Docker config at the start of the operation.\n * Pass \"{}\" to disable discovery and use no registry credentials.\n */\n dockerConfigJson?: string;\n\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 * Import as a CAS (content-addressed streaming) image through the Image\n * Service instead of a legacy template. Off by default.\n */\n cas?: boolean;\n /**\n * CAS imports only (`cas: true`): aborting requests remote cancellation of\n * the Image Service import; see `CreateSandboxImageOptions.signal`.\n */\n signal?: AbortSignal;\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 dockerConfigJson?: string | undefined | null;\n}\n\ninterface NativeBindingOptions extends NativeBindingCommonOptions {\n dockerfilePath: string;\n dockerfileText?: string | undefined | null;\n contextDir?: string | undefined | null;\n cas?: boolean | undefined | null;\n buildArgs?: Record<string, string> | undefined | null;\n}\n\ninterface NativeBindingImportOptions extends NativeBindingCommonOptions {\n imageReference: string;\n cas?: boolean | undefined | null;\n}\n\n/** Credentials and scope for the merged image catalog. */\ninterface NativeBindingCatalogOptions {\n apiUrl: string;\n bearerToken: string;\n organizationId?: string | undefined | null;\n projectId?: string | undefined | null;\n useScopeHeaders?: boolean | undefined | null;\n userAgent?: string | undefined | null;\n}\n\ninterface NativeBindingEvent {\n eventType: string;\n stream?: string | undefined | null;\n message: string;\n /** CAS build events (`build_accepted`, `build_progress`, `build_terminal`, `interrupted`). */\n buildId?: string | undefined | null;\n clientRequestId?: string | undefined | null;\n status?: string | undefined | null;\n phase?: string | undefined | null;\n attempt?: number | undefined | null;\n outcome?: string | undefined | null;\n confirmed?: boolean | undefined | null;\n}\n\n/** Credentials and scope for build lookups, waits and cancellations. */\ninterface NativeBindingBuildClientOptions {\n apiUrl: string;\n bearerToken: string;\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}\n\ninterface NativeBinding {\n loadDockerConfigJson(): string;\n /** `interruptId` is honored for CAS builds only; legacy builds ignore it. */\n buildSandboxImage(\n options: NativeBindingOptions,\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n interruptId?: number | undefined | null,\n ): Promise<string>;\n importSandboxImage(\n options: NativeBindingImportOptions,\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n interruptId?: number | undefined | null,\n ): Promise<string>;\n // --- Image Service build operations (CAS only) ---\n createImageBuildInterrupt(): number;\n triggerImageBuildInterrupt(id: number): void;\n releaseImageBuildInterrupt(id: number): void;\n /** JSON `{build, client_request_id}` after admission (and context seal). */\n startImageBuild(\n options: Omit<NativeBindingOptions, \"builderDiskMb\" | \"dockerCompat\">,\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n interruptId?: number | undefined | null,\n ): Promise<string>;\n startImageImport(\n options: Omit<NativeBindingImportOptions, \"builderDiskMb\" | \"dockerCompat\">,\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n interruptId?: number | undefined | null,\n ): Promise<string>;\n /** BuildInfo JSON. */\n getImageBuild(options: NativeBindingBuildClientOptions, buildId: string): Promise<string>;\n /** The build's immutable result JSON. */\n waitImageBuild(\n options: NativeBindingBuildClientOptions,\n buildId: string,\n wait: { timeoutMs?: number | undefined | null; followLogs?: boolean | undefined | null },\n emit?: ((event: NativeBindingEvent) => void) | null | undefined,\n interruptId?: number | undefined | null,\n ): Promise<string>;\n /** JSON `{outcome, build}`. */\n cancelImageBuild(\n options: NativeBindingBuildClientOptions,\n selector: { buildId?: string | undefined | null; clientRequestId?: string | undefined | null },\n ): Promise<string>;\n /** JSON array of every image of both families, newest first. */\n listSandboxImages(options: NativeBindingCatalogOptions): Promise<string>;\n /** JSON record of one image by name or id, or null when unknown. */\n findSandboxImage(\n options: NativeBindingCatalogOptions,\n reference: string,\n ): Promise<string | null>;\n /** Delete one image by name or id; unknown in both catalogs rejects. */\n deleteSandboxImage(\n options: NativeBindingCatalogOptions,\n reference: string,\n ): Promise<void>;\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 // CAS build events carry structured state beside the message.\n if (event.buildId != null) out.build_id = event.buildId;\n if (event.clientRequestId !== undefined && event.eventType !== \"status\") {\n out.client_request_id = event.clientRequestId;\n }\n if (event.status != null) out.status = event.status;\n if (event.phase !== undefined && event.eventType.startsWith(\"build_\")) out.phase = event.phase;\n if (event.attempt != null) out.attempt = event.attempt;\n if (event.outcome != null) out.outcome = event.outcome;\n if (event.confirmed != null) out.confirmed = event.confirmed;\n return out;\n}\n\n/**\n * @internal Shared with `image-builds.ts`, which implements the Image\n * Service build operations on top of the same native binding and\n * environment context.\n */\nexport const __imageBuildInternals = {\n loadNativeBinding: () => loadNativeBinding(),\n buildContextFromEnv: () => buildContextFromEnv(),\n stderrEmit: (event: Record<string, unknown>) => stderrEmit(event),\n noopEmit: (event: Record<string, unknown>) => noopEmit(event),\n eventToEmitDict: (event: NativeBindingEvent) => eventToEmitDict(event),\n imageRequiresContext: (image: Image) => imageRequiresContext(image),\n defaultRegisteredName: (dockerfilePath: string) => defaultRegisteredName(dockerfilePath),\n defaultRegisteredNameFromImage: (reference: string) =>\n defaultRegisteredNameFromImage(reference),\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 if (options.signal !== undefined && !options.cas) {\n throw new Error(\n \"signal is only supported for CAS image builds (cas: true); a legacy build has no \" +\n \"Image Service build operation to cancel\",\n );\n }\n\n emit({ type: \"status\", message: `Building image '${effectiveName}'...` });\n\n const binding = loadNativeBinding();\n let emitError: unknown;\n const nativeOptions = {\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 dockerConfigJson: options.dockerConfigJson,\n dockerfileText,\n contextDir: nativeContextDir,\n cas: options.cas ?? false,\n buildArgs: options.buildArgs,\n };\n const forward = (event: NativeBindingEvent) => {\n try {\n emit(eventToEmitDict(event));\n } catch (error) {\n emitError ??= error;\n }\n };\n // CAS builds run through the interrupt-aware bridge so an AbortSignal\n // reaches the Rust cancellation handshake and typed build errors are\n // decoded. Legacy builds keep the plain call and its error path.\n const resultJson = options.cas\n ? await __runWithInterrupt(options.signal, (interruptId) =>\n binding.buildSandboxImage(nativeOptions, forward, interruptId),\n )\n : await binding.buildSandboxImage(nativeOptions, forward);\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 if (options.signal !== undefined && !options.cas) {\n throw new Error(\n \"signal is only supported for CAS image imports (cas: true); a legacy import has no \" +\n \"Image Service build operation to cancel\",\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 nativeOptions = {\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 dockerConfigJson: options.dockerConfigJson,\n cas: options.cas ?? false,\n };\n const forward = (event: NativeBindingEvent) => {\n try {\n emit(eventToEmitDict(event));\n } catch (error) {\n emitError ??= error;\n }\n };\n const resultJson = options.cas\n ? await __runWithInterrupt(options.signal, (interruptId) =>\n binding.importSandboxImage(nativeOptions, forward, interruptId),\n )\n : await binding.importSandboxImage(nativeOptions, forward);\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\n/** Credentials the merged-catalog operations run with. */\nexport interface SandboxImageCatalogCredentials {\n apiUrl?: string;\n apiKey?: string;\n organizationId?: string;\n projectId?: string;\n}\n\nfunction catalogOptionsFromEnv(): NativeBindingCatalogOptions {\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 return { apiUrl: context.apiUrl, bearerToken, useScopeHeaders: false };\n}\n\n// An explicit organization/project pair addresses that project's routes\n// directly (and sends the scope headers), as the clients' explicit-scope\n// options always did; without one the key's own scope applies. The Rust core\n// reads the pair only when `useScopeHeaders` is set, so the flag follows the\n// pair. Half a pair is a caller error rather than a silent fallback.\nfunction catalogOptionsFromCredentials(\n credentials: SandboxImageCatalogCredentials,\n): NativeBindingCatalogOptions {\n const context = buildContextFromEnv();\n const bearerToken = credentials.apiKey ?? context.apiKey;\n if (!bearerToken) {\n throw new Error(\"Missing TENSORLAKE_API_KEY credentials.\");\n }\n const { organizationId, projectId } = credentials;\n if ((organizationId === undefined) !== (projectId === undefined)) {\n throw new TypeError(\"organizationId and projectId must be given together\");\n }\n return {\n apiUrl: credentials.apiUrl ?? context.apiUrl,\n bearerToken,\n organizationId,\n projectId,\n useScopeHeaders: organizationId !== undefined,\n };\n}\n\nfunction parseTemplate(json: string): SandboxTemplate {\n return JSON.parse(json) as SandboxTemplate;\n}\n\n/**\n * Delete a registered sandbox image by name or id. Both families are\n * covered: an `image_` id or a name registered in the Image Service deletes\n * a CAS image, a `sandbox_template_` id or a name registered only in the\n * platform registry deletes a legacy image. Rejects when neither catalog\n * knows the reference.\n *\n * Deleting removes a *published* image. An unfinished CAS build is cancelled\n * with `cancelImageBuild({ buildId })` (or `tl sbx image build cancel\n * BUILD_ID`), never by deleting its name: a name whose only state is an\n * unfinished first build has no image, so the Image Service answers 404 and\n * the lookup falls through to the platform registry as usual. A 202\n * (deletion in progress) counts as success; a 409 `image_build_in_progress`,\n * a 5xx or a transport failure rejects as is and never falls through.\n *\n * Accepted merged-catalog differences from the released SDKs, for legacy\n * images: this deletes the platform-api template itself (the released SDKs\n * only removed the engine registration and left the template listed), and\n * an unknown name rejects instead of succeeding silently.\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 await loadNativeBinding().deleteSandboxImage(catalogOptionsFromEnv(), imageName);\n}\n\n/** @internal `APIClient.deleteSandboxImage` with the client's credentials. */\nexport async function deleteSandboxImageWithCredentials(\n credentials: SandboxImageCatalogCredentials,\n imageName: string,\n): Promise<void> {\n if (typeof imageName !== \"string\" || imageName.length === 0) {\n throw new TypeError(\"imageName must be a non-empty string\");\n }\n await loadNativeBinding().deleteSandboxImage(\n catalogOptionsFromCredentials(credentials),\n imageName,\n );\n}\n\n/**\n * Look up a registered sandbox image by its registered name or id.\n *\n * Returns the image in the sandbox-template shape (CAS images carry\n * `snapshotFormatVersion === \"content_addressed_streaming_v1\"`; the shape is\n * derived from the Image Service's trimmed record, so no content digest or\n * build provenance rides on it), or `null` if neither the Image Service nor\n * the platform registry knows the reference. Uses the same environment-based Tensorlake\n * auth as `createSandboxImage`. Ingress derives project scope from the API key.\n *\n * An `image_` id names the *current* image under its name; a rebuild\n * replaces it. A build's own immutable result is read with `getImageBuild`.\n *\n * Accepted merged-catalog difference from the released SDKs, for legacy\n * images: a name that fits the Image Service grammar is looked up there first\n * and only a clean 404 falls through to the platform registry, so Image\n * Service unavailability (or a deploy 5xx) rejects the lookup of a legacy name\n * where the released SDKs touched only platform-api. A `sandbox_template_` id\n * never consults the Image Service.\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 const json = await loadNativeBinding().findSandboxImage(\n catalogOptionsFromEnv(),\n imageName,\n );\n return json == null ? null : parseTemplate(json);\n}\n\n/** @internal `CloudClient.findSandboxImageByName` with the client's credentials. */\nexport async function findSandboxImageByNameWithCredentials(\n credentials: SandboxImageCatalogCredentials,\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 const json = await loadNativeBinding().findSandboxImage(\n catalogOptionsFromCredentials(credentials),\n imageName,\n );\n return json == null ? null : parseTemplate(json);\n}\n\n/**\n * List all registered sandbox images for the current project: every CAS and\n * legacy image in the sandbox-template shape, newest first. Uses the same\n * environment-based Tensorlake auth as `createSandboxImage`. Ingress derives\n * project scope from the API key.\n */\nexport async function listSandboxImages(): Promise<SandboxTemplate[]> {\n const json = await loadNativeBinding().listSandboxImages(catalogOptionsFromEnv());\n return JSON.parse(json) as SandboxTemplate[];\n}\n\n/** @internal `CloudClient.listSandboxImages` with the client's credentials. */\nexport async function listSandboxImagesWithCredentials(\n credentials: SandboxImageCatalogCredentials,\n): Promise<SandboxTemplate[]> {\n const json = await loadNativeBinding().listSandboxImages(\n catalogOptionsFromCredentials(credentials),\n );\n return JSON.parse(json) as SandboxTemplate[];\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 MiB] [--disk_mb MiB] [--builder_disk_mb MiB] [--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 const dockerConfigJson = loadNativeBinding().loadDockerConfigJson();\n await createSandboxImage(\n dockerfilePath,\n {\n registeredName: parsed.values.name,\n dockerConfigJson,\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 MiB] [--disk_mb MiB] [--builder_disk_mb MiB] [--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 const dockerConfigJson = loadNativeBinding().loadDockerConfigJson();\n await importSandboxImage(\n imageReference,\n {\n registeredName: parsed.values.name,\n dockerConfigJson,\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,SAAS,kBAAkB;AA+B3B,SAAS,eAAe,IAA8C;AACpE,SAAO;AAAA,IACL,MAAM,GAAG;AAAA,IACT,MAAM,CAAC,GAAG,GAAG,IAAI;AAAA,IACjB,SAAS,EAAE,GAAG,GAAG,QAAQ;AAAA,EAC3B;AACF;AAsHA,SAAS,cAAc,SAAyC;AAC9D,QAAM,UAAU,OAAO,QA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C,qBAAqB,MAAM,oBAAoB;AAAA,MAC/C,YAAY,CAAC,UAAmC,WAAW,KAAK;AAAA,MAChE,UAAU,CAAC,UAAmC,SAAS,KAAK;AAAA,MAC5D,iBAAiB,CAAC,UAA8B,gBAAgB,KAAK;AAAA,MACrE,sBAAsB,CAAC,UAAiB,qBAAqB,KAAK;AAAA,MAClE,uBAAuB,CAAC,mBAA2B,sBAAsB,cAAc;AAAA,MACvF,gCAAgC,CAAC,cAC/B,+BAA+B,SAAS;AAAA,IAC5C;AAAA;AAAA;","names":["createSandboxImage","detectLinuxLibc","fs","read","count","path","fileURLToPath","require","path","existsSync","ImageBuildStatus","ImageBuildPhase","ImageBuildKind","ImageBuildCancellationOutcome","ImageBuildErrorCode","path","os","existsSync","mkdtempSync","rmSync","DEFAULT_IMAGE_NAME"]}