@tensorlakeai/tensorlake 0.5.154 → 0.5.157
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/applications/index.cjs +131 -40
- package/dist/applications/index.cjs.map +1 -1
- package/dist/applications/index.d.cts +3 -3
- package/dist/applications/index.d.ts +3 -3
- package/dist/applications/index.js +131 -40
- package/dist/applications/index.js.map +1 -1
- package/dist/function-agent/main.cjs +1 -1
- package/dist/function-agent/main.js +1 -1
- package/dist/function-executor/main.cjs +2 -2
- package/dist/function-executor/main.js +2 -2
- package/dist/index.cjs +175 -62
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +31 -23
- package/dist/index.d.ts +31 -23
- package/dist/index.js +175 -62
- package/dist/index.js.map +1 -1
- package/dist/{remote-B3vn4tt1.d.cts → remote-CEs4GFGP.d.cts} +1 -1
- package/dist/{remote-DqBUuciu.d.ts → remote-DYBXCTNC.d.ts} +1 -1
- package/dist/{sandbox-image-BMiFlzAs.d.cts → sandbox-image-C2GTVnx3.d.cts} +99 -52
- package/dist/{sandbox-image-BMiFlzAs.d.ts → sandbox-image-C2GTVnx3.d.ts} +99 -52
- package/dist/sandbox-image.cjs +119 -30
- package/dist/sandbox-image.cjs.map +1 -1
- package/dist/sandbox-image.d.cts +1 -1
- package/dist/sandbox-image.d.ts +1 -1
- package/dist/sandbox-image.js +119 -30
- package/dist/sandbox-image.js.map +1 -1
- package/package.json +7 -7
- package/runtime/function-executor/manifest.json +5 -5
- package/runtime/function-executor/package/dist/function-executor/main.js +2 -2
- package/runtime/function-executor/package/npm-shrinkwrap.json +2 -2
- package/runtime/function-executor/package/package.json +1 -1
- package/runtime/typescript-function-runner/manifest.json +5 -5
- package/runtime/typescript-function-runner/package/dist/function-agent/main.js +1 -1
- package/runtime/typescript-function-runner/package/npm-shrinkwrap.json +26 -26
- package/runtime/typescript-function-runner/package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
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;AA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AU,OAAO,OAAO;AAAA,IAC1B;AAAA,IACA,EAAE,MAAM,kBAAkB,WAAW,KAAK;AAAA,EAC5C;AACF;AA5/BA,IA4PI,qBACA,0BAqDEA,qBAuEO;AAzXb;AAAA;AAAA;AAKA;AAEA;AACA;AA0SA,IAAMA,sBAAqB;AAuEpB,IAAM,wBAAwB;AAAA,MACnC,mBAAmB,MAAM,kBAAkB;AAAA,MAC3C,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"]}
|
|
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 and register it as a CAS sandbox image (the default) or,\n * with `cas: false`, a legacy sandbox image.\n *\n * Materializes the image in a build sandbox, snapshots the filesystem,\n * and registers the snapshot under the image's name.\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 * Build operations for CAS sandbox images.\n *\n * A CAS (content-addressed streaming) image is built or imported by a *build\n * 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 images only.** Everything here addresses a CAS image build. Legacy\n * images (`createSandboxImage` with `cas: false`, `sandbox_template_` ids,\n * `.tlsnap` 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/** A CAS image 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 CAS image of a succeeded build, in the sandbox-template\n * shape the merged catalog answers (derived by the core from the CAS image\n * registry's trimmed record): one image representation for\n * `findSandboxImageByName`, `listSandboxImages` and build results.\n */\nexport type ImageBuildResult = SandboxTemplate;\n\n/**\n * One CAS image build or import as the 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 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 image 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 a CAS image id, not a build id; look the CAS 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 = __imageBuildInternals.registeredImageName(\n options.registeredName ?? source.name,\n undefined,\n true,\n );\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 = __imageBuildInternals.registeredImageName(\n options.registeredName,\n __imageBuildInternals.defaultRegisteredName(resolved),\n true,\n );\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 CAS 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 = __imageBuildInternals.registeredImageName(\n options.registeredName,\n __imageBuildInternals.defaultRegisteredNameFromImage(reference),\n true,\n __imageBuildInternals.defaultImportedImageName,\n );\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 '${reference}' as CAS image '${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 /**\n * Name to register the image under. Defaults to the image's `name` or the\n * Dockerfile stem (the parent directory's name for a file named\n * `Dockerfile`).\n * A CAS image name is lowercased, as the CAS image registry stores it; a\n * default CAS image name is also made valid (other characters become `-`).\n * Legacy image names are kept as given.\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, the default. Pass\n * `false` to build a legacy image instead.\n */\n cas?: boolean;\n /**\n * Dockerfile build args (`--build-arg KEY=VALUE`), forwarded to BuildKit\n * and expanded in `FROM` references. CAS images only; a legacy image build\n * with build args is rejected.\n */\n buildArgs?: Record<string, string>;\n /**\n * CAS images only: aborting requests *remote cancellation* of the CAS\n * image build through a bounded handshake, and the call rejects with\n * `ImageBuildInterruptedError` carrying the outcome. It is rejected for a\n * legacy image build (`cas: false`), which has no build operation to\n * cancel. 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 * A CAS image name is lowercased, as the CAS image registry stores it; a\n * default CAS image name is also made valid (other characters become `-`).\n * Legacy image names are kept as given.\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, the default. Pass\n * `false` to import a legacy image instead.\n */\n cas?: boolean;\n /**\n * CAS images only: aborting requests remote cancellation of the CAS image\n * 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 // --- CAS image build operations ---\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 /**\n * Delete one image by name or id; a name is deleted from both catalogs.\n * Unknown in both catalogs rejects. Resolves to the same-named legacy\n * image a name's CAS delete could not remove, or null.\n */\n deleteSandboxImage(\n options: NativeBindingCatalogOptions,\n reference: string,\n ): Promise<NativeLegacyCleanupFailure | null | undefined>;\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\";\nconst DEFAULT_SANDBOX_IMAGE_NAME = \"sandbox-image\";\nconst DEFAULT_IMPORTED_IMAGE_NAME = \"imported-image\";\nconst CAS_NAME_SEPARATORS = \"._-\";\nconst RESERVED_IMAGE_NAME_PREFIXES = [\"sandbox_template_\", \"image_\", \"cas-v1:\"];\nconst MAX_CAS_IMAGE_NAME_LENGTH = 255;\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 || DEFAULT_SANDBOX_IMAGE_NAME;\n }\n return parsed.name || DEFAULT_SANDBOX_IMAGE_NAME;\n}\n\n/**\n * Mirror the Rust core's `registered_image_name`: the name a build or import\n * registers, decided before anything is shown or sent. A CAS image takes the\n * CAS image registry's spelling: an explicit name is lowercased as the\n * registry would, and a generated default is turned into a valid CAS image\n * name. Legacy image names are kept as they are.\n */\nfunction registeredImageName(\n explicit: string | undefined,\n generated: string | undefined,\n cas: boolean,\n fallback: string = DEFAULT_SANDBOX_IMAGE_NAME,\n): string {\n if (explicit || generated === undefined) {\n const name = explicit ?? \"\";\n return cas ? canonicalCasImageName(name) : name;\n }\n return cas ? casImageNameFrom(generated, fallback) : generated;\n}\n\n/**\n * Mirror the Rust core's `canonical_cas_image_name`: the CAS image registry\n * ASCII-lowercases every name, so `MyProject` and `myproject` name one CAS\n * image.\n */\nfunction canonicalCasImageName(name: string): string {\n return name.replace(/[A-Z]/g, (c) => c.toLowerCase());\n}\n\n/**\n * Mirror the Rust core's `cas_image_name_from`: a valid CAS image name for a\n * generated default. The name is ASCII-lowercased and kept if that makes it\n * valid. Otherwise every character other than `a-z`, `0-9`, `.`, `_` and `-`\n * becomes `-`, each run of separators collapses to its first character,\n * leading and trailing separators are dropped and the result is capped at\n * 255 characters. `fallback` is used when no valid name remains.\n */\nfunction casImageNameFrom(raw: string, fallback: string): string {\n const lowered = canonicalCasImageName(raw);\n if (isAddressableCasImageName(lowered)) {\n return lowered;\n }\n let name = \"\";\n for (const original of lowered) {\n const ch = /^[a-z0-9._-]$/.test(original) ? original : \"-\";\n const previous = name[name.length - 1];\n if (\n CAS_NAME_SEPARATORS.includes(ch) &&\n previous !== undefined &&\n CAS_NAME_SEPARATORS.includes(previous)\n ) {\n continue;\n }\n name += ch;\n }\n name = name\n .replace(/^[._-]+|[._-]+$/g, \"\")\n .slice(0, MAX_CAS_IMAGE_NAME_LENGTH)\n .replace(/[._-]+$/, \"\");\n return isAddressableCasImageName(name) ? name : fallback;\n}\n\n/**\n * Mirror the Rust core's CAS image name grammar: valid in the CAS image\n * registry and not mistaken for a content digest.\n */\nfunction isAddressableCasImageName(name: string): boolean {\n if (\n name.length === 0 ||\n name.length > MAX_CAS_IMAGE_NAME_LENGTH ||\n RESERVED_IMAGE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix)) ||\n /^[0-9a-f]{64}$/.test(name)\n ) {\n return false;\n }\n const colon = name.indexOf(\":\");\n const repository = colon === -1 ? name : name.slice(0, colon);\n if (!repository.split(\"/\").every((component) => /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(component))) {\n return false;\n }\n if (colon === -1) {\n return true;\n }\n const tag = name.slice(colon + 1);\n return (\n tag.length > 0 &&\n tag.length <= 128 &&\n /^[a-z0-9._-]+$/.test(tag) &&\n !tag.startsWith(\".\") &&\n !tag.startsWith(\"-\")\n );\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 || DEFAULT_IMPORTED_IMAGE_NAME;\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 CAS image\n * build operations on top of the same native binding and environment\n * 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 registeredImageName: (\n explicit: string | undefined,\n generated: string | undefined,\n cas: boolean,\n fallback?: string,\n ) => registeredImageName(explicit, generated, cas, fallback),\n casImageNameFrom: (raw: string, fallback: string) => casImageNameFrom(raw, fallback),\n canonicalCasImageName: (name: string) => canonicalCasImageName(name),\n isAddressableCasImageName: (name: string) => isAddressableCasImageName(name),\n defaultImportedImageName: DEFAULT_IMPORTED_IMAGE_NAME,\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 = registeredImageName(\n options.registeredName ?? source.name,\n undefined,\n options.cas ?? true,\n );\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 = registeredImageName(\n options.registeredName,\n defaultRegisteredName(resolvedPath),\n options.cas ?? true,\n );\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 const cas = options.cas ?? true;\n if (options.signal !== undefined && !cas) {\n throw new Error(\n \"signal is not supported for legacy image builds (cas: false): a legacy image build \" +\n \"has no build operation to cancel\",\n );\n }\n\n emit({\n type: \"status\",\n message: `Building ${cas ? \"CAS\" : \"legacy\"} image '${effectiveName}'...`,\n });\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,\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 image builds run through the interrupt-aware bridge so an\n // AbortSignal reaches the Rust cancellation handshake and typed build\n // errors are decoded. Legacy image builds keep the plain call and its\n // error path.\n const resultJson = 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 = registeredImageName(\n options.registeredName,\n defaultRegisteredNameFromImage(reference),\n options.cas ?? true,\n DEFAULT_IMPORTED_IMAGE_NAME,\n );\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 const cas = options.cas ?? true;\n if (options.signal !== undefined && !cas) {\n throw new Error(\n \"signal is not supported for legacy image imports (cas: false): a legacy image import \" +\n \"has no build operation to cancel\",\n );\n }\n\n emit({\n type: \"status\",\n message: `Importing '${reference}' as ${cas ? \"CAS\" : \"legacy\"} image '${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,\n };\n const forward = (event: NativeBindingEvent) => {\n try {\n emit(eventToEmitDict(event));\n } catch (error) {\n emitError ??= error;\n }\n };\n const resultJson = 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 CAS or legacy sandbox image by name or id. Both\n * families are covered: an `image_` id or a name registered in the CAS image\n * registry deletes a CAS image, a `sandbox_template_` id or a name registered\n * only in the legacy image registry deletes a legacy image. Rejects when\n * neither the CAS nor the legacy image registry knows the reference.\n *\n * A name is deleted from both the CAS and the legacy image registries: once\n * its CAS image is deleted, a legacy image of the same name can no longer\n * start sandboxes, so it is deleted too. CAS image names ignore case\n * (`MyProject` deletes the CAS image `myproject`), legacy image names match\n * exactly. Failing to delete that legacy image\n * does not reject, since the CAS image is already gone: a `console.warn`\n * names the legacy image, the error and the call that deletes it. An\n * `image_` or `sandbox_template_` id deletes only the image it names.\n *\n * Deleting removes a *published* image. An unfinished CAS image build is\n * cancelled with `cancelImageBuild({ buildId })` (or `tl sbx image build\n * cancel BUILD_ID`), never by deleting its name: a name whose only state is\n * an unfinished first build has no CAS image, so the CAS image registry\n * answers 404 and the lookup falls through to the legacy image registry as\n * usual. A 202 (deletion in progress) counts as success; a 409\n * `image_build_in_progress`, a 5xx or a transport failure rejects as is and\n * never falls through.\n *\n * Accepted merged-catalog differences from the released SDKs, for legacy\n * images: this removes the legacy image from the legacy image registry (the\n * released SDKs only made it unusable and left it listed), and an unknown\n * 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 warnIncompleteLegacyCleanup(\n await loadNativeBinding().deleteSandboxImage(catalogOptionsFromEnv(), imageName),\n );\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 warnIncompleteLegacyCleanup(\n await loadNativeBinding().deleteSandboxImage(\n catalogOptionsFromCredentials(credentials),\n imageName,\n ),\n );\n}\n\n/**\n * The same-named legacy image a name's CAS delete could not remove. Its name\n * is the deleted CAS image's name, in the CAS image registry's lowercase\n * spelling.\n */\ninterface NativeLegacyCleanupFailure {\n legacyImageName: string;\n legacyImageId?: string | null;\n error: string;\n}\n\n// The CAS image is gone, so the delete succeeded; report the legacy image it\n// left behind, which can no longer start sandboxes, and how to delete it.\n// Legacy names are case-sensitive, so recovery uses the returned name rather\n// than the caller's spelling.\nfunction warnIncompleteLegacyCleanup(\n failure: NativeLegacyCleanupFailure | null | undefined,\n): void {\n if (failure == null) {\n return;\n }\n const legacyImageId = failure.legacyImageId ?? undefined;\n const label = legacyImageId ? ` (${legacyImageId})` : \"\";\n console.warn(\n `Deleted CAS image '${failure.legacyImageName}', but could not delete the legacy ` +\n `image of the same name${label}, which can no longer start sandboxes: ` +\n `${failure.error}. Delete it with ` +\n `deleteSandboxImage(\"${legacyImageId ?? failure.legacyImageName}\").`,\n );\n}\n\n/**\n * Look up a registered CAS or legacy sandbox image by its registered name or\n * 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 CAS image registry's trimmed record, so no content digest\n * or build provenance rides on it), or `null` if neither the CAS nor the\n * legacy image registry knows the reference. Uses the same environment-based\n * Tensorlake auth as `createSandboxImage`. Ingress derives project scope from\n * the API key.\n *\n * An `image_` id names the *current* CAS image under its name; a rebuild\n * replaces it. A build's own immutable result is read with `getImageBuild`.\n *\n * A name is looked up in the CAS image registry in lowercase, as the\n * registry stores it, and in the legacy image registry exactly as given.\n *\n * Accepted merged-catalog difference from the released SDKs, for legacy\n * images: a name that fits the CAS image registry's grammar is looked up\n * there first and only a clean 404 falls through to the legacy image\n * registry, so CAS image registry unavailability (or a deploy 5xx) rejects\n * the lookup of a legacy image name where the released SDKs touched only the\n * legacy image registry. A `sandbox_template_` id never consults the CAS\n * image registry.\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 \"no-cas\": { 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] [--no-cas]\",\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 cas: !parsed.values[\"no-cas\"],\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 \"no-cas\": { 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] [--no-cas]\",\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 cas: !parsed.values[\"no-cas\"],\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,GAA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AoB;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,MAC1C,qBAAqB,CACnB,UACA,WACA,KACA,aACG,oBAAoB,UAAU,WAAW,KAAK,QAAQ;AAAA,MAC3D,kBAAkB,CAAC,KAAa,aAAqB,iBAAiB,KAAK,QAAQ;AAAA,MACnF,uBAAuB,CAAC,SAAiB,sBAAsB,IAAI;AAAA,MACnE,2BAA2B,CAAC,SAAiB,0BAA0B,IAAI;AAAA,MAC3E,0BAA0B;AAAA,IAC5B;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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tensorlakeai/tensorlake",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.157",
|
|
4
4
|
"description": "TensorLake SDK for applications, sandboxes, and cloud services",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -98,11 +98,11 @@
|
|
|
98
98
|
"ws": "^8.20.0"
|
|
99
99
|
},
|
|
100
100
|
"optionalDependencies": {
|
|
101
|
-
"@tensorlakeai/native-darwin-arm64": "0.5.
|
|
102
|
-
"@tensorlakeai/native-linux-arm64-gnu": "0.5.
|
|
103
|
-
"@tensorlakeai/native-linux-arm64-musl": "0.5.
|
|
104
|
-
"@tensorlakeai/native-linux-x64-gnu": "0.5.
|
|
105
|
-
"@tensorlakeai/native-linux-x64-musl": "0.5.
|
|
106
|
-
"@tensorlakeai/native-win32-x64": "0.5.
|
|
101
|
+
"@tensorlakeai/native-darwin-arm64": "0.5.157",
|
|
102
|
+
"@tensorlakeai/native-linux-arm64-gnu": "0.5.157",
|
|
103
|
+
"@tensorlakeai/native-linux-arm64-musl": "0.5.157",
|
|
104
|
+
"@tensorlakeai/native-linux-x64-gnu": "0.5.157",
|
|
105
|
+
"@tensorlakeai/native-linux-x64-musl": "0.5.157",
|
|
106
|
+
"@tensorlakeai/native-win32-x64": "0.5.157"
|
|
107
107
|
}
|
|
108
108
|
}
|