@tensorlakeai/tensorlake 0.5.151 → 0.5.153

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +8 -0
  2. package/dist/applications/index.cjs +3510 -3384
  3. package/dist/applications/index.cjs.map +1 -1
  4. package/dist/applications/index.d.cts +3 -3
  5. package/dist/applications/index.d.ts +3 -3
  6. package/dist/applications/index.js +3286 -3160
  7. package/dist/applications/index.js.map +1 -1
  8. package/dist/function-agent/main.cjs +1 -1
  9. package/dist/function-agent/main.cjs.map +1 -1
  10. package/dist/function-agent/main.js +1 -1
  11. package/dist/function-agent/main.js.map +1 -1
  12. package/dist/function-executor/main.cjs +2 -2
  13. package/dist/function-executor/main.cjs.map +1 -1
  14. package/dist/function-executor/main.js +2 -2
  15. package/dist/function-executor/main.js.map +1 -1
  16. package/dist/index.cjs +1424 -1079
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +313 -27
  19. package/dist/index.d.ts +313 -27
  20. package/dist/index.js +1401 -1069
  21. package/dist/index.js.map +1 -1
  22. package/dist/{remote-CC48cvYP.d.cts → remote-B3vn4tt1.d.cts} +1 -1
  23. package/dist/{remote-BbSrvgUn.d.ts → remote-DqBUuciu.d.ts} +1 -1
  24. package/dist/{sandbox-image-CAK_K7ND.d.cts → sandbox-image-BMiFlzAs.d.cts} +168 -13
  25. package/dist/{sandbox-image-CAK_K7ND.d.ts → sandbox-image-BMiFlzAs.d.ts} +168 -13
  26. package/dist/sandbox-image.cjs +339 -1295
  27. package/dist/sandbox-image.cjs.map +1 -1
  28. package/dist/sandbox-image.d.cts +1 -1
  29. package/dist/sandbox-image.d.ts +1 -1
  30. package/dist/sandbox-image.js +338 -1294
  31. package/dist/sandbox-image.js.map +1 -1
  32. package/package.json +8 -7
  33. package/runtime/function-executor/manifest.json +7 -7
  34. package/runtime/function-executor/package/dist/function-executor/main.js +2 -2
  35. package/runtime/function-executor/package/dist/function-executor/main.js.map +1 -1
  36. package/runtime/function-executor/package/npm-shrinkwrap.json +2 -2
  37. package/runtime/function-executor/package/package.json +1 -1
  38. package/runtime/typescript-function-runner/manifest.json +7 -7
  39. package/runtime/typescript-function-runner/package/dist/function-agent/main.js +1 -1
  40. package/runtime/typescript-function-runner/package/dist/function-agent/main.js.map +1 -1
  41. package/runtime/typescript-function-runner/package/npm-shrinkwrap.json +26 -26
  42. package/runtime/typescript-function-runner/package/package.json +7 -7
@@ -40,1179 +40,6 @@ var init_esm_shims = __esm({
40
40
  }
41
41
  });
42
42
 
43
- // src/defaults.ts
44
- var SDK_VERSION, API_URL, API_KEY, NAMESPACE, SANDBOX_PROXY_URL, DEFAULT_HTTP_TIMEOUT_MS, MAX_RETRIES, RETRY_BACKOFF_MS;
45
- var init_defaults = __esm({
46
- "src/defaults.ts"() {
47
- "use strict";
48
- init_esm_shims();
49
- SDK_VERSION = "0.5.151";
50
- API_URL = process.env.TENSORLAKE_API_URL ?? "https://api.tensorlake.ai";
51
- API_KEY = process.env.TENSORLAKE_API_KEY ?? void 0;
52
- NAMESPACE = process.env.INDEXIFY_NAMESPACE ?? "default";
53
- SANDBOX_PROXY_URL = process.env.TENSORLAKE_SANDBOX_PROXY_URL ?? "https://sandbox.tensorlake.ai";
54
- DEFAULT_HTTP_TIMEOUT_MS = 3e5;
55
- MAX_RETRIES = 3;
56
- RETRY_BACKOFF_MS = 500;
57
- }
58
- });
59
-
60
- // src/models.ts
61
- function snakeToCamel(str) {
62
- return str.replace(/_([a-z])/g, (_, ch) => ch.toUpperCase());
63
- }
64
- function parseTimestamp(v) {
65
- if (v == null) return void 0;
66
- if (v instanceof Date) return v;
67
- if (typeof v === "string") {
68
- const parsed = Date.parse(v);
69
- return Number.isNaN(parsed) ? void 0 : new Date(parsed);
70
- }
71
- const ts = Number(v);
72
- if (isNaN(ts)) return void 0;
73
- if (ts > 1e15) return new Date(ts / 1e3);
74
- if (ts > 1e12) return new Date(ts);
75
- return new Date(ts * 1e3);
76
- }
77
- function fromSnakeKeys(obj, idField) {
78
- if (Array.isArray(obj))
79
- return obj.map((item) => fromSnakeKeys(item, idField));
80
- if (obj !== null && typeof obj === "object" && !(obj instanceof Date)) {
81
- const result = {};
82
- for (const [k, v] of Object.entries(obj)) {
83
- let key;
84
- if (k === "id" && idField) {
85
- key = idField;
86
- } else {
87
- key = snakeToCamel(k);
88
- }
89
- if (key.endsWith("At") || key === "timestamp" || key === "startedAt" || key === "endedAt") {
90
- result[key] = parseTimestamp(v);
91
- } else if (typeof v === "object" && v !== null && !Array.isArray(v)) {
92
- result[key] = fromSnakeKeys(v);
93
- } else if (Array.isArray(v)) {
94
- result[key] = v.map((item) => fromSnakeKeys(item));
95
- } else {
96
- result[key] = v === null ? void 0 : v;
97
- }
98
- }
99
- return result;
100
- }
101
- return obj;
102
- }
103
- var CommandExitReason;
104
- var init_models = __esm({
105
- "src/models.ts"() {
106
- "use strict";
107
- init_esm_shims();
108
- CommandExitReason = /* @__PURE__ */ ((CommandExitReason2) => {
109
- CommandExitReason2["EXITED"] = "exited";
110
- CommandExitReason2["SIGNALED"] = "signaled";
111
- CommandExitReason2["OOM_KILLED"] = "oom_killed";
112
- CommandExitReason2["TIMED_OUT"] = "timed_out";
113
- return CommandExitReason2;
114
- })(CommandExitReason || {});
115
- }
116
- });
117
-
118
- // src/errors.ts
119
- function formatErrorDetails(errorDetails) {
120
- if (errorDetails == null) return void 0;
121
- if (typeof errorDetails === "string") {
122
- const detail = errorDetails.trim();
123
- return detail || void 0;
124
- }
125
- if (Array.isArray(errorDetails)) {
126
- const parts = errorDetails.map((item) => formatErrorDetails(item)).filter((item) => Boolean(item));
127
- return parts.length > 0 ? parts.join("; ") : JSON.stringify(errorDetails);
128
- }
129
- if (typeof errorDetails === "object") {
130
- for (const key of ["message", "detail", "error", "reason"]) {
131
- const value = errorDetails[key];
132
- if (typeof value === "string" && value.trim()) {
133
- return value.trim();
134
- }
135
- }
136
- return JSON.stringify(errorDetails);
137
- }
138
- return String(errorDetails);
139
- }
140
- var SandboxException, SandboxError, SandboxResizeError, SandboxConnectionError, SandboxNotFoundError, PoolNotFoundError, PoolInUseError, RemoteAPIError;
141
- var init_errors = __esm({
142
- "src/errors.ts"() {
143
- "use strict";
144
- init_esm_shims();
145
- SandboxException = class extends Error {
146
- constructor(message) {
147
- super(message);
148
- this.name = "SandboxException";
149
- }
150
- };
151
- SandboxError = class extends SandboxException {
152
- reason;
153
- sandboxId;
154
- constructor(message, options) {
155
- super(message);
156
- this.name = "SandboxError";
157
- if (options?.reason !== void 0) this.reason = options.reason;
158
- if (options?.sandboxId !== void 0) this.sandboxId = options.sandboxId;
159
- }
160
- };
161
- SandboxResizeError = class extends SandboxError {
162
- generation;
163
- info;
164
- constructor(payload) {
165
- const resources = payload.info?.resources;
166
- const allocation = resources ? `${resources.cpus} CPUs, ${resources.memoryMb} MiB memory, ${resources.diskMb} MiB disk` : "unavailable";
167
- super(
168
- `Sandbox ${payload.sandboxId} resize generation ${payload.generation}: ${payload.message}; last confirmed allocation: ${allocation}`,
169
- { reason: payload.reason, sandboxId: payload.sandboxId }
170
- );
171
- this.name = "SandboxResizeError";
172
- this.generation = payload.generation;
173
- this.info = payload.info ?? void 0;
174
- }
175
- /** Last confirmed allocation, if an observation was available. */
176
- get confirmedResources() {
177
- return this.info?.resources;
178
- }
179
- };
180
- SandboxConnectionError = class extends SandboxError {
181
- constructor(message, options) {
182
- super(`Connection error: ${message}`);
183
- this.name = "SandboxConnectionError";
184
- if (options?.cause !== void 0) this.cause = options.cause;
185
- }
186
- };
187
- SandboxNotFoundError = class extends SandboxError {
188
- constructor(sandboxId) {
189
- super(`Sandbox not found: ${sandboxId}`, { sandboxId });
190
- this.name = "SandboxNotFoundError";
191
- }
192
- };
193
- PoolNotFoundError = class extends SandboxError {
194
- poolId;
195
- constructor(poolId) {
196
- super(`Sandbox pool not found: ${poolId}`);
197
- this.name = "PoolNotFoundError";
198
- this.poolId = poolId;
199
- }
200
- };
201
- PoolInUseError = class extends SandboxError {
202
- poolId;
203
- constructor(poolId, message) {
204
- const base = `Cannot delete pool ${poolId}: pool is in use`;
205
- super(message ? `${base} - ${message}` : base);
206
- this.name = "PoolInUseError";
207
- this.poolId = poolId;
208
- }
209
- };
210
- RemoteAPIError = class extends SandboxError {
211
- statusCode;
212
- /** Original response body, retained for compatibility and diagnostics. */
213
- responseMessage;
214
- errorDetails;
215
- constructor(statusCode, message) {
216
- let failure;
217
- try {
218
- const payload = JSON.parse(message);
219
- if (payload && typeof payload === "object" && !Array.isArray(payload)) {
220
- const record = payload;
221
- if (typeof record.sandbox_id === "string" && record.sandbox_id.trim() && (record.status === "failed" || record.status === "terminated"))
222
- failure = record;
223
- }
224
- } catch {
225
- }
226
- const sandboxId = failure?.sandbox_id;
227
- const rawReason = failure?.reason ?? failure?.termination_reason;
228
- const reason = typeof rawReason === "string" ? rawReason : void 0;
229
- const errorDetails = failure?.error_details;
230
- let displayMessage = message;
231
- if (failure) {
232
- displayMessage = `Sandbox ${sandboxId} ${failure.status}`;
233
- if (reason) displayMessage += ` (${reason})`;
234
- const detail = formatErrorDetails(errorDetails);
235
- if (detail) displayMessage += `: ${detail}`;
236
- if (!reason && !detail) displayMessage = message;
237
- }
238
- super(`API error (status ${statusCode}): ${displayMessage}`, {
239
- reason,
240
- sandboxId
241
- });
242
- this.errorDetails = errorDetails;
243
- this.name = "RemoteAPIError";
244
- this.statusCode = statusCode;
245
- this.responseMessage = message;
246
- }
247
- };
248
- }
249
- });
250
-
251
- // src/native-worker-protocol.ts
252
- var cancelNativeCall, closeNativeHandle;
253
- var init_native_worker_protocol = __esm({
254
- "src/native-worker-protocol.ts"() {
255
- "use strict";
256
- init_esm_shims();
257
- cancelNativeCall = /* @__PURE__ */ Symbol.for("tensorlake.native.cancel.v1");
258
- closeNativeHandle = /* @__PURE__ */ Symbol.for("tensorlake.native.close.v1");
259
- }
260
- });
261
-
262
- // src/url.ts
263
- function trimTrailingSlashes(url) {
264
- return url.endsWith("/") ? url.slice(0, -1) : url;
265
- }
266
- function resolveProxyTarget(proxyUrl, sandboxId) {
267
- try {
268
- const parsed = new URL(proxyUrl);
269
- const host = parsed.hostname;
270
- if (host === "localhost" || host === "127.0.0.1") {
271
- return {
272
- baseUrl: trimTrailingSlashes(proxyUrl),
273
- hostHeader: `${sandboxId}.local`,
274
- sandboxIdHeader: void 0
275
- };
276
- }
277
- const port = parsed.port ? `:${parsed.port}` : "";
278
- return {
279
- baseUrl: `${parsed.protocol}//${host}${port}`,
280
- hostHeader: void 0,
281
- sandboxIdHeader: sandboxId
282
- };
283
- } catch {
284
- return {
285
- baseUrl: `${trimTrailingSlashes(proxyUrl)}/${sandboxId}`,
286
- hostHeader: void 0,
287
- sandboxIdHeader: void 0
288
- };
289
- }
290
- }
291
- var init_url = __esm({
292
- "src/url.ts"() {
293
- "use strict";
294
- init_esm_shims();
295
- init_defaults();
296
- }
297
- });
298
-
299
- // src/native-worker-client.ts
300
- import { createRequire } from "module";
301
- import { Worker } from "worker_threads";
302
- function createWorkerBinding(runtime) {
303
- return {
304
- NativeCloudClient: class {
305
- constructor(...args) {
306
- return runtime.handle("NativeCloudClient", args);
307
- }
308
- },
309
- NativeSandboxClient: class {
310
- constructor(...args) {
311
- return runtime.handle("NativeSandboxClient", args);
312
- }
313
- },
314
- NativeSandboxProxyClient: class {
315
- constructor(...args) {
316
- return runtime.handle("NativeSandboxProxyClient", args);
317
- }
318
- },
319
- NativeRepositoryClient: class {
320
- constructor(...args) {
321
- return runtime.handle("NativeRepositoryClient", args);
322
- }
323
- },
324
- validateManagedName: (name) => runtime.call(void 0, "validateManagedName", [name])
325
- };
326
- }
327
- function workerBinding() {
328
- return createWorkerBinding(
329
- runtimes[runtimeKey] ??= new NativeWorkerClient()
330
- );
331
- }
332
- function releaseNativeHandle(handle) {
333
- handle?.[closeNativeHandle]?.();
334
- }
335
- var NativeWorkerClient, runtimeKey, runtimes;
336
- var init_native_worker_client = __esm({
337
- "src/native-worker-client.ts"() {
338
- "use strict";
339
- init_esm_shims();
340
- init_native_worker_protocol();
341
- init_url();
342
- NativeWorkerClient = class {
343
- constructor(workerPath = () => createRequire(import.meta.url).resolve(
344
- "@tensorlakeai/tensorlake/internal/native-worker"
345
- )) {
346
- this.workerPath = workerPath;
347
- }
348
- worker;
349
- nextId = 1;
350
- registered = /* @__PURE__ */ new Set();
351
- pending = /* @__PURE__ */ new Map();
352
- finalizers = new FinalizationRegistry(
353
- (id) => this.release(id)
354
- );
355
- handle(kind, args, parent) {
356
- const handle = { id: this.nextId++, kind, args, parent };
357
- this.finalizers.register(handle, handle.id);
358
- let closed = false;
359
- return new Proxy(
360
- {},
361
- {
362
- get: (_target, method) => {
363
- if (method === "then") return void 0;
364
- if (method === closeNativeHandle)
365
- return () => {
366
- closed = true;
367
- this.release(handle.id);
368
- };
369
- if (method === "connectProxy")
370
- return (...proxyArgs) => {
371
- if (closed) throw new Error("Tensorlake native client is closed");
372
- return this.handle("NativeSandboxProxyClient", proxyArgs, handle);
373
- };
374
- if (method === "baseUrl")
375
- return () => resolveProxyTarget(String(args[0]), String(args[1])).baseUrl;
376
- if (typeof method !== "string") return void 0;
377
- return (...callArgs) => {
378
- if (closed)
379
- return Promise.reject(
380
- new Error("Tensorlake native client is closed")
381
- );
382
- const emit = typeof callArgs.at(-1) === "function" ? callArgs.pop() : void 0;
383
- return this.call(handle, method, callArgs, emit);
384
- };
385
- }
386
- }
387
- );
388
- }
389
- call(handle, method, args, emit) {
390
- const id = this.nextId++;
391
- let worker;
392
- const promise = new Promise((resolve, reject) => {
393
- try {
394
- worker = this.getWorker();
395
- this.pending.set(id, { resolve, reject, emit, handle });
396
- worker.ref();
397
- if (handle) this.register(handle, worker);
398
- this.send(worker, {
399
- type: "call",
400
- id,
401
- handleId: handle?.id,
402
- method,
403
- args,
404
- stream: !!emit
405
- });
406
- } catch (error) {
407
- this.pending.delete(id);
408
- this.unrefIfIdle();
409
- reject(error);
410
- }
411
- });
412
- promise[cancelNativeCall] = () => {
413
- const pending = this.pending.get(id);
414
- if (pending && worker) {
415
- pending.emit = void 0;
416
- this.send(worker, { type: "cancel", id });
417
- }
418
- };
419
- return promise;
420
- }
421
- getWorker() {
422
- if (this.worker) return this.worker;
423
- const worker = new Worker(this.workerPath(), {
424
- // The bundled worker needs no application loaders or telemetry preloads.
425
- // NODE_OPTIONS is parsed independently of execArgv by Node.
426
- execArgv: [],
427
- env: { ...process.env, NODE_OPTIONS: "" },
428
- name: "tensorlake-native"
429
- });
430
- this.worker = worker;
431
- worker.on("message", (message) => {
432
- const pending = this.pending.get(message.id);
433
- if (!pending || this.worker !== worker) return;
434
- if (message.type === "event") {
435
- Promise.resolve().then(() => pending.emit?.(message.value)).then(
436
- () => {
437
- if (this.worker === worker)
438
- this.send(worker, { type: "ack", id: message.id });
439
- },
440
- (error) => {
441
- this.send(worker, { type: "cancel", id: message.id });
442
- pending.reject(error);
443
- }
444
- );
445
- return;
446
- }
447
- this.pending.delete(message.id);
448
- if (message.type === "error") {
449
- const error = new Error(message.error.message);
450
- error.name = message.error.name;
451
- error.stack = message.error.stack ?? error.stack;
452
- pending.reject(error);
453
- } else {
454
- pending.resolve(message.value);
455
- }
456
- this.unrefIfIdle();
457
- });
458
- const fail = (error) => {
459
- if (this.worker !== worker) return;
460
- this.worker = void 0;
461
- this.registered.clear();
462
- for (const pending of this.pending.values()) pending.reject(error);
463
- this.pending.clear();
464
- void worker.terminate();
465
- };
466
- worker.on("error", fail);
467
- worker.on("messageerror", fail);
468
- worker.on(
469
- "exit",
470
- (code) => fail(
471
- new Error(
472
- `Tensorlake native worker exited (${code}); in-flight operations were not retried`
473
- )
474
- )
475
- );
476
- worker.unref();
477
- return worker;
478
- }
479
- register(handle, worker) {
480
- if (this.registered.has(handle.id)) return;
481
- if (handle.parent) this.register(handle.parent, worker);
482
- this.send(worker, {
483
- type: "create",
484
- handle: { id: handle.id, kind: handle.kind, args: handle.args },
485
- parentId: handle.parent?.id
486
- });
487
- this.registered.add(handle.id);
488
- }
489
- release(handleId) {
490
- if (this.worker && this.registered.delete(handleId))
491
- this.send(this.worker, { type: "release", handleId });
492
- }
493
- send(worker, message) {
494
- worker.postMessage(message);
495
- }
496
- unrefIfIdle() {
497
- if (this.pending.size === 0) this.worker?.unref();
498
- }
499
- };
500
- runtimeKey = /* @__PURE__ */ Symbol.for(
501
- `tensorlake.native.worker.${false ? "source" : "0.5.151"}.v1`
502
- );
503
- runtimes = globalThis;
504
- }
505
- });
506
-
507
- // src/native-sandbox.ts
508
- function loadNativeSandboxBinding() {
509
- return cachedBinding ??= workerBinding();
510
- }
511
- function parseNativeError(error) {
512
- const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
513
- if (!message) return null;
514
- try {
515
- const parsed = JSON.parse(message);
516
- if (parsed && typeof parsed.category === "string") {
517
- return {
518
- category: parsed.category,
519
- status: typeof parsed.status === "number" ? parsed.status : null,
520
- message: typeof parsed.message === "string" ? parsed.message : message
521
- };
522
- }
523
- } catch {
524
- }
525
- return null;
526
- }
527
- function translateNativeError(error, context) {
528
- const payload = parseNativeError(error);
529
- if (!payload) {
530
- if (error instanceof Error) return error;
531
- return new SandboxError(String(error));
532
- }
533
- const { category, status, message } = payload;
534
- if (category === "resize") {
535
- return new SandboxResizeError(
536
- fromSnakeKeys(JSON.parse(message), "sandboxId")
537
- );
538
- }
539
- if (category === "connection") {
540
- return new SandboxConnectionError(message, { cause: error });
541
- }
542
- if (status === 404) {
543
- if (context?.notFoundKind === "pool" && context.poolId) {
544
- return new PoolNotFoundError(context.poolId);
545
- }
546
- if (context?.notFoundKind === "sandbox" && context.sandboxId) {
547
- return new SandboxNotFoundError(context.sandboxId);
548
- }
549
- return new RemoteAPIError(404, message);
550
- }
551
- if (status === 409 && context?.poolId) {
552
- return new PoolInUseError(context.poolId, message);
553
- }
554
- if (typeof status === "number") {
555
- return new RemoteAPIError(status, message);
556
- }
557
- return new SandboxError(message);
558
- }
559
- async function callNative(fn, context) {
560
- try {
561
- return await fn();
562
- } catch (error) {
563
- throw translateNativeError(error, context);
564
- }
565
- }
566
- async function* nativeEventStream(start, context, signal) {
567
- if (signal?.aborted) return;
568
- const queue = [];
569
- let wake;
570
- let finished = false;
571
- let stopped = false;
572
- let failure;
573
- const notify = () => {
574
- const resolve = wake;
575
- wake = void 0;
576
- resolve?.();
577
- };
578
- const emit = (value) => {
579
- if (stopped) return Promise.resolve();
580
- return new Promise((consumed) => {
581
- queue.push({ value, consumed });
582
- notify();
583
- });
584
- };
585
- let call;
586
- const onAbort = () => {
587
- stopped = true;
588
- call?.[cancelNativeCall]?.();
589
- notify();
590
- };
591
- signal?.addEventListener("abort", onAbort, { once: true });
592
- try {
593
- call = start(emit);
594
- void call.catch((error) => {
595
- failure = error;
596
- }).finally(() => {
597
- finished = true;
598
- notify();
599
- });
600
- while (!stopped) {
601
- const event = queue.shift();
602
- if (event) {
603
- try {
604
- yield JSON.parse(event.value);
605
- } finally {
606
- event.consumed();
607
- }
608
- } else if (finished) {
609
- break;
610
- } else {
611
- await new Promise((resolve) => {
612
- wake = resolve;
613
- });
614
- }
615
- }
616
- if (!stopped && failure !== void 0) throw translateNativeError(failure, context);
617
- } finally {
618
- stopped = true;
619
- signal?.removeEventListener("abort", onAbort);
620
- call?.[cancelNativeCall]?.();
621
- for (const event of queue) event.consumed();
622
- }
623
- }
624
- var cachedBinding, KNOWN_EXIT_REASONS;
625
- var init_native_sandbox = __esm({
626
- "src/native-sandbox.ts"() {
627
- "use strict";
628
- init_esm_shims();
629
- init_models();
630
- init_errors();
631
- init_native_worker_client();
632
- init_native_worker_protocol();
633
- KNOWN_EXIT_REASONS = new Set(Object.values(CommandExitReason));
634
- }
635
- });
636
-
637
- // src/native-cloud.ts
638
- async function serializeRequest(method, path4, options) {
639
- const headers = { ...options?.headers };
640
- let body = options?.body;
641
- if (options?.json !== void 0) {
642
- body = JSON.stringify(options.json);
643
- if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {
644
- headers["Content-Type"] = "application/json";
645
- }
646
- }
647
- const request = {
648
- method,
649
- path: path4,
650
- headersJson: JSON.stringify(headers),
651
- statusOnlyCodes: [...options?.statusOnlyCodes ?? []]
652
- };
653
- if (body instanceof FormData) {
654
- request.parts = [];
655
- for (const [name, value] of body.entries()) {
656
- request.parts.push(typeof value === "string" ? { name, data: Buffer.from(value) } : { name, data: Buffer.from(await value.arrayBuffer()), filename: value.name, contentType: value.type || "application/octet-stream" });
657
- }
658
- } else if (body !== void 0) {
659
- if (body instanceof Blob) request.body = Buffer.from(await body.arrayBuffer());
660
- else if (typeof body === "string") request.body = Buffer.from(body);
661
- else if (body instanceof ArrayBuffer) request.body = Buffer.from(new Uint8Array(body));
662
- else request.body = Buffer.from(body);
663
- }
664
- return request;
665
- }
666
- var NativeCloudTransport;
667
- var init_native_cloud = __esm({
668
- "src/native-cloud.ts"() {
669
- "use strict";
670
- init_esm_shims();
671
- init_native_sandbox();
672
- init_native_worker_client();
673
- NativeCloudTransport = class {
674
- constructor(options) {
675
- this.options = options;
676
- if (!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0 || options.maxRetries > 4294967295) {
677
- throw new RangeError("maxRetries must be a non-negative 32-bit integer");
678
- }
679
- if (!Number.isFinite(options.retryBackoffMs) || options.retryBackoffMs < 0) {
680
- throw new RangeError("retryBackoffMs must be a non-negative finite number");
681
- }
682
- }
683
- native;
684
- closed = false;
685
- client() {
686
- if (this.closed) throw new Error("Tensorlake native client is closed");
687
- if (this.native) return this.native;
688
- const ctor = loadNativeSandboxBinding().NativeCloudClient;
689
- if (!ctor) throw new Error("Native binding does not export NativeCloudClient; rebuild with 'npm run build:native'");
690
- return this.native = new ctor(JSON.stringify(this.options));
691
- }
692
- close() {
693
- this.closed = true;
694
- releaseNativeHandle(this.native ?? null);
695
- this.native = void 0;
696
- }
697
- async requestResponse(method, path4, options) {
698
- const request = await serializeRequest(method, path4, options);
699
- const raw = await callNative(() => this.client().request(request));
700
- const response = new Response(
701
- [204, 205, 304].includes(raw.status) ? null : Uint8Array.from(raw.data).buffer,
702
- { status: raw.status, headers: JSON.parse(raw.headersJson) }
703
- );
704
- return Object.assign(response, { traceId: raw.traceId });
705
- }
706
- async requestJson(method, path4) {
707
- const response = await this.requestResponse(method, path4);
708
- const text = await response.text();
709
- const value = text ? JSON.parse(text) : null;
710
- return Object.assign(value ?? {}, { traceId: response.traceId });
711
- }
712
- async *stream(method, path4, signal) {
713
- if (signal?.aborted) return;
714
- const request = await serializeRequest(method, path4, { headers: { Accept: "text/event-stream" } });
715
- yield* nativeEventStream((emit) => this.client().stream(request, emit), void 0, signal);
716
- }
717
- };
718
- }
719
- });
720
-
721
- // src/cloud-client.ts
722
- import { nanoid } from "nanoid";
723
- function secretFromMetadata(metadata) {
724
- return {
725
- id: metadata.id,
726
- name: metadata.name,
727
- createdAt: new Date(metadata.created_at_ms)
728
- };
729
- }
730
- function applicationAllowsUnauthenticatedRequests(manifest) {
731
- return Array.isArray(manifest.allow) && manifest.allow.includes(UNAUTHENTICATED_REQUESTS);
732
- }
733
- function publicEndpointIdFromManifest(manifest) {
734
- for (const key of ["public_endpoint_id", "publicEndpointId"]) {
735
- const value = manifest[key];
736
- if (typeof value === "string" && value.length > 0) {
737
- return value;
738
- }
739
- }
740
- return void 0;
741
- }
742
- function generatePublicEndpointId() {
743
- return `endpoint_${nanoid()}`;
744
- }
745
- function createApplicationBuildForm(request, imageContexts) {
746
- const contextsByPartName = /* @__PURE__ */ new Map();
747
- for (const context of imageContexts) {
748
- if (contextsByPartName.has(context.contextTarPartName)) {
749
- throw new Error(
750
- `duplicate image context part name '${context.contextTarPartName}'`
751
- );
752
- }
753
- contextsByPartName.set(context.contextTarPartName, context);
754
- }
755
- const form = new FormData();
756
- form.append(
757
- "app_version",
758
- new Blob([JSON.stringify(request)], { type: "application/json" }),
759
- "app_version"
760
- );
761
- for (const image of request.images) {
762
- const context = contextsByPartName.get(image.contextTarPartName);
763
- if (!context) {
764
- throw new Error(
765
- `missing image context for part '${image.contextTarPartName}'`
766
- );
767
- }
768
- form.append(
769
- image.contextTarPartName,
770
- new Blob([toBlobPart(context.contextTarGz)]),
771
- `${image.contextTarPartName}.tar.gz`
772
- );
773
- }
774
- for (const context of imageContexts) {
775
- if (!request.images.some((image) => image.contextTarPartName === context.contextTarPartName)) {
776
- throw new Error(
777
- `unexpected image context for part '${context.contextTarPartName}'`
778
- );
779
- }
780
- }
781
- return form;
782
- }
783
- function trimTrailingSlashes2(value) {
784
- return value.endsWith("/") ? value.slice(0, -1) : value;
785
- }
786
- function nextRequestPath(next) {
787
- const schemeIndex = next.indexOf("://");
788
- if (schemeIndex !== -1) {
789
- const afterScheme = next.slice(schemeIndex + 3);
790
- const slashIndex = afterScheme.indexOf("/");
791
- return slashIndex === -1 ? "/" : afterScheme.slice(slashIndex);
792
- }
793
- return next.startsWith("/") ? next : `/${next}`;
794
- }
795
- function toBlobPart(data) {
796
- if (typeof data === "string" || data instanceof Blob) {
797
- return data;
798
- }
799
- if (data instanceof Uint8Array) {
800
- return Uint8Array.from(data).buffer;
801
- }
802
- return data;
803
- }
804
- function toRequestBody(data) {
805
- return toBlobPart(data);
806
- }
807
- async function parseJsonResponse(response) {
808
- const text = await response.text();
809
- if (!text) {
810
- return void 0;
811
- }
812
- return JSON.parse(text);
813
- }
814
- var CloudClient, UNAUTHENTICATED_REQUESTS;
815
- var init_cloud_client = __esm({
816
- "src/cloud-client.ts"() {
817
- "use strict";
818
- init_esm_shims();
819
- init_defaults();
820
- init_native_cloud();
821
- init_models();
822
- CloudClient = class _CloudClient {
823
- transport;
824
- organizationId;
825
- projectId;
826
- namespace;
827
- constructor(options) {
828
- this.organizationId = options?.organizationId;
829
- this.projectId = options?.projectId;
830
- this.namespace = options?.namespace ?? NAMESPACE;
831
- this.transport = new NativeCloudTransport({
832
- baseUrl: options?.apiUrl ?? API_URL,
833
- apiKey: options?.apiKey ?? API_KEY,
834
- organizationId: this.organizationId,
835
- projectId: this.projectId,
836
- maxRetries: options?.maxRetries ?? MAX_RETRIES,
837
- retryBackoffMs: options?.retryBackoffMs ?? RETRY_BACKOFF_MS,
838
- timeoutMs: DEFAULT_HTTP_TIMEOUT_MS,
839
- userAgent: `tensorlake-typescript-sdk/${SDK_VERSION}`
840
- });
841
- }
842
- static forCloud(options) {
843
- return new _CloudClient(options);
844
- }
845
- close() {
846
- this.transport.close();
847
- }
848
- async upsertApplication(manifest, codeZip, upgradeRunningRequests = false) {
849
- const applicationManifest = { ...manifest };
850
- let publicEndpointId = publicEndpointIdFromManifest(applicationManifest);
851
- if (applicationAllowsUnauthenticatedRequests(applicationManifest) && publicEndpointId === void 0) {
852
- const applicationName = applicationManifest.name;
853
- if (typeof applicationName === "string" && applicationName.length > 0) {
854
- publicEndpointId = await this.existingApplicationPublicEndpointId(applicationName);
855
- }
856
- publicEndpointId ??= generatePublicEndpointId();
857
- }
858
- if (publicEndpointId !== void 0) {
859
- applicationManifest.public_endpoint_id = publicEndpointId;
860
- delete applicationManifest.publicEndpointId;
861
- }
862
- const form = new FormData();
863
- form.append(
864
- "code",
865
- new Blob([toBlobPart(codeZip)], { type: "application/zip" }),
866
- "code.zip"
867
- );
868
- form.append("code_content_type", "application/zip");
869
- form.append("application", JSON.stringify(applicationManifest));
870
- form.append(
871
- "upgrade_requests_to_latest_code",
872
- String(upgradeRunningRequests)
873
- );
874
- await this.transport.requestResponse("POST", this.namespacePath("applications"), {
875
- body: form
876
- });
877
- }
878
- async deleteApplication(applicationName) {
879
- await this.transport.requestResponse(
880
- "DELETE",
881
- this.namespacePath(`applications/${encodeURIComponent(applicationName)}`)
882
- );
883
- }
884
- async deleteSandboxImage(imageName) {
885
- await this.transport.requestResponse(
886
- "DELETE",
887
- this.namespacePath(`sandbox-images/${encodeURIComponent(imageName)}`)
888
- );
889
- }
890
- /**
891
- * Look up a registered sandbox image (template) by its registered name.
892
- *
893
- * Returns the template, or `null` when no image with that name exists.
894
- * API-key clients may omit organization/project IDs and use the
895
- * token-scoped Platform API route directly. Explicit scope remains
896
- * available for PAT callers.
897
- */
898
- async findSandboxImageByName(imageName, options) {
899
- const base = this.platformProjectPath(
900
- "sandbox-templates",
901
- options?.organizationId,
902
- options?.projectId
903
- );
904
- const response = await this.transport.requestResponse(
905
- "GET",
906
- `${base}/by-name/${encodeURIComponent(imageName)}`,
907
- { statusOnlyCodes: /* @__PURE__ */ new Set([404]) }
908
- );
909
- if (response.status === 404) {
910
- return null;
911
- }
912
- const raw = await parseJsonResponse(response);
913
- return fromSnakeKeys(raw);
914
- }
915
- /**
916
- * List all registered sandbox images (templates), following pagination to
917
- * the end. API-key clients may omit organization/project IDs and use the
918
- * token-scoped Platform API route directly.
919
- */
920
- async listSandboxImages(options) {
921
- const base = this.platformProjectPath(
922
- "sandbox-templates",
923
- options?.organizationId,
924
- options?.projectId
925
- );
926
- let path4 = `${base}?pageSize=100`;
927
- const templates = [];
928
- while (path4 !== null) {
929
- const page = await this.transport.requestJson(
930
- "GET",
931
- path4
932
- );
933
- for (const item of page.items ?? []) {
934
- templates.push(fromSnakeKeys(item));
935
- }
936
- const next = page.pagination?.next;
937
- path4 = next ? nextRequestPath(next) : null;
938
- }
939
- return templates;
940
- }
941
- async applications() {
942
- const raw = await this.transport.requestJson(
943
- "GET",
944
- this.namespacePath("applications")
945
- );
946
- return (raw.applications ?? []).map(
947
- (application) => fromSnakeKeys(application)
948
- );
949
- }
950
- async applicationManifest(applicationName) {
951
- const raw = await this.transport.requestJson(
952
- "GET",
953
- this.namespacePath(`applications/${encodeURIComponent(applicationName)}`)
954
- );
955
- return fromSnakeKeys(raw);
956
- }
957
- async runRequest(applicationName, inputs = []) {
958
- const path4 = this.namespacePath(
959
- `applications/${encodeURIComponent(applicationName)}`
960
- );
961
- const response = inputs.length === 0 ? await this.transport.requestResponse("POST", path4, {
962
- body: new Uint8Array(),
963
- headers: { Accept: "application/json" }
964
- }) : inputs.length === 1 && inputs[0].name === "0" ? await this.transport.requestResponse("POST", path4, {
965
- body: toRequestBody(inputs[0].data),
966
- headers: {
967
- Accept: "application/json",
968
- "Content-Type": inputs[0].contentType
969
- }
970
- }) : await this.runMultipartRequest(path4, inputs);
971
- const body = await parseJsonResponse(response);
972
- const requestId = body?.request_id;
973
- if (!requestId) {
974
- throw new Error("missing request_id in run request response body");
975
- }
976
- return requestId;
977
- }
978
- async waitOnRequestCompletion(applicationName, requestId) {
979
- const stream = this.transport.stream(
980
- "GET",
981
- this.namespacePath(
982
- `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/progress`
983
- )
984
- );
985
- for await (const event of stream) {
986
- if (Object.prototype.hasOwnProperty.call(event, "RequestFinished")) {
987
- return;
988
- }
989
- }
990
- throw new Error("progress stream ended before request completion");
991
- }
992
- async requestMetadata(applicationName, requestId) {
993
- const raw = await this.transport.requestJson(
994
- "GET",
995
- this.namespacePath(
996
- `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}`
997
- )
998
- );
999
- return fromSnakeKeys(raw);
1000
- }
1001
- async requestOutput(applicationName, requestId) {
1002
- const response = await this.transport.requestResponse(
1003
- "GET",
1004
- this.namespacePath(
1005
- `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/output`
1006
- )
1007
- );
1008
- const serializedValue = new Uint8Array(await response.arrayBuffer());
1009
- const contentType = response.headers.get("content-type") ?? "";
1010
- return {
1011
- serializedValue,
1012
- contentType
1013
- };
1014
- }
1015
- async listSecrets(options) {
1016
- const base = this.secretCollectionPath(
1017
- options?.organizationId,
1018
- options?.projectId
1019
- );
1020
- const raw = await this.transport.requestJson("GET", base);
1021
- const pageSize = Math.max(0, options?.pageSize ?? 100);
1022
- return Object.assign(
1023
- {
1024
- items: raw.slice(0, pageSize).map(secretFromMetadata),
1025
- pagination: { total: raw.length }
1026
- },
1027
- { traceId: raw.traceId }
1028
- );
1029
- }
1030
- async getSecret(secretId, options) {
1031
- const base = this.secretCollectionPath(
1032
- options?.organizationId,
1033
- options?.projectId
1034
- );
1035
- const raw = await this.transport.requestJson(
1036
- "GET",
1037
- `${base}/${encodeURIComponent(secretId)}`
1038
- );
1039
- return Object.assign(secretFromMetadata(raw), { traceId: raw.traceId });
1040
- }
1041
- async upsertSecrets(secrets, options) {
1042
- const base = this.secretCollectionPath(
1043
- options?.organizationId,
1044
- options?.projectId
1045
- );
1046
- if (Array.isArray(secrets)) {
1047
- const results = [];
1048
- for (const secret of secrets) {
1049
- results.push(await this.upsertSecret(base, secret));
1050
- }
1051
- return results;
1052
- }
1053
- return this.upsertSecret(base, secrets);
1054
- }
1055
- async deleteSecret(secretId, options) {
1056
- const base = this.secretCollectionPath(
1057
- options?.organizationId,
1058
- options?.projectId
1059
- );
1060
- await this.transport.requestResponse(
1061
- "DELETE",
1062
- `${base}/${encodeURIComponent(secretId)}`
1063
- );
1064
- }
1065
- async upsertSecret(base, secret) {
1066
- let response = await this.transport.requestResponse("POST", base, {
1067
- json: secret,
1068
- headers: { "Idempotency-Key": nanoid() },
1069
- statusOnlyCodes: /* @__PURE__ */ new Set([409])
1070
- });
1071
- if (response.status === 409) {
1072
- const prefix = base.slice(0, -"/secrets".length);
1073
- const existing = await this.transport.requestJson(
1074
- "GET",
1075
- `${prefix}/secret-names/${encodeURIComponent(secret.name)}`
1076
- );
1077
- response = await this.transport.requestResponse(
1078
- "POST",
1079
- `${base}/${encodeURIComponent(existing.id)}/versions`,
1080
- {
1081
- json: { value: secret.value },
1082
- headers: { "Idempotency-Key": nanoid() }
1083
- }
1084
- );
1085
- }
1086
- const metadata = await parseJsonResponse(response);
1087
- return Object.assign(secretFromMetadata(metadata), {
1088
- traceId: response.traceId
1089
- });
1090
- }
1091
- async startImageBuild(buildServicePath, request) {
1092
- const form = new FormData();
1093
- form.append("graph_name", request.applicationName);
1094
- form.append("graph_version", request.applicationVersion);
1095
- form.append("graph_function_name", request.functionName);
1096
- form.append("image_name", request.imageName);
1097
- form.append("image_id", request.imageId);
1098
- form.append(
1099
- "context",
1100
- new Blob([toBlobPart(request.buildContext)]),
1101
- "context.tar.gz"
1102
- );
1103
- const response = await this.transport.requestResponse(
1104
- "PUT",
1105
- `${trimTrailingSlashes2(buildServicePath)}/builds`,
1106
- { body: form }
1107
- );
1108
- const raw = await parseJsonResponse(response);
1109
- return fromSnakeKeys(raw);
1110
- }
1111
- async createApplicationBuild(buildServicePath, request, imageContexts) {
1112
- const form = createApplicationBuildForm(request, imageContexts);
1113
- const response = await this.transport.requestResponse(
1114
- "POST",
1115
- trimTrailingSlashes2(buildServicePath),
1116
- { body: form }
1117
- );
1118
- const raw = await parseJsonResponse(response);
1119
- return fromSnakeKeys(raw);
1120
- }
1121
- async applicationBuildInfo(buildServicePath, applicationBuildId) {
1122
- const raw = await this.transport.requestJson(
1123
- "GET",
1124
- `${trimTrailingSlashes2(buildServicePath)}/${encodeURIComponent(applicationBuildId)}`
1125
- );
1126
- return fromSnakeKeys(raw);
1127
- }
1128
- async cancelApplicationBuild(buildServicePath, applicationBuildId) {
1129
- const raw = await this.transport.requestJson(
1130
- "POST",
1131
- `${trimTrailingSlashes2(buildServicePath)}/${encodeURIComponent(applicationBuildId)}/cancel`
1132
- );
1133
- return fromSnakeKeys(raw);
1134
- }
1135
- async buildInfo(buildServicePath, buildId) {
1136
- const raw = await this.transport.requestJson(
1137
- "GET",
1138
- `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}`
1139
- );
1140
- return fromSnakeKeys(raw);
1141
- }
1142
- async cancelBuild(buildServicePath, buildId) {
1143
- await this.transport.requestResponse(
1144
- "POST",
1145
- `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}/cancel`
1146
- );
1147
- }
1148
- async *streamBuildLogs(buildServicePath, buildId, signal) {
1149
- const stream = this.transport.stream(
1150
- "GET",
1151
- `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}/logs`,
1152
- signal
1153
- );
1154
- for await (const event of stream) {
1155
- yield fromSnakeKeys(event);
1156
- }
1157
- }
1158
- async runMultipartRequest(path4, inputs) {
1159
- const form = new FormData();
1160
- for (const input of inputs) {
1161
- form.append(
1162
- input.name,
1163
- new Blob([toBlobPart(input.data)], { type: input.contentType }),
1164
- input.name
1165
- );
1166
- }
1167
- return this.transport.requestResponse("POST", path4, {
1168
- body: form,
1169
- headers: { Accept: "application/json" }
1170
- });
1171
- }
1172
- namespacePath(subpath) {
1173
- return `/v1/namespaces/${encodeURIComponent(this.namespace)}/${subpath.replace(/^\/+/, "")}`;
1174
- }
1175
- async existingApplicationPublicEndpointId(applicationName) {
1176
- const response = await this.transport.requestResponse(
1177
- "GET",
1178
- this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),
1179
- { statusOnlyCodes: /* @__PURE__ */ new Set([404]) }
1180
- );
1181
- if (response.status === 404) {
1182
- return void 0;
1183
- }
1184
- const application = await parseJsonResponse(response);
1185
- return publicEndpointIdFromManifest(application);
1186
- }
1187
- platformProjectPath(resource, organizationId, projectId) {
1188
- const resolvedOrganizationId = organizationId ?? this.organizationId;
1189
- const resolvedProjectId = projectId ?? this.projectId;
1190
- if (!resolvedOrganizationId && !resolvedProjectId) {
1191
- return `/platform/v1/${resource}`;
1192
- }
1193
- if (!resolvedOrganizationId || !resolvedProjectId) {
1194
- throw new Error(
1195
- "organizationId and projectId must be provided together"
1196
- );
1197
- }
1198
- return `/platform/v1/organizations/${encodeURIComponent(resolvedOrganizationId)}/projects/${encodeURIComponent(resolvedProjectId)}/${resource}`;
1199
- }
1200
- secretCollectionPath(organizationId, projectId) {
1201
- const resolvedOrganizationId = organizationId ?? this.organizationId;
1202
- const resolvedProjectId = projectId ?? this.projectId;
1203
- if (!resolvedOrganizationId && !resolvedProjectId) {
1204
- return this.namespacePath("secrets");
1205
- }
1206
- if (!resolvedOrganizationId || !resolvedProjectId) {
1207
- throw new Error("organizationId and projectId must be provided together");
1208
- }
1209
- return this.namespacePath("secrets");
1210
- }
1211
- };
1212
- UNAUTHENTICATED_REQUESTS = "unauthenticated_requests";
1213
- }
1214
- });
1215
-
1216
43
  // src/image.ts
1217
44
  import { randomUUID } from "crypto";
1218
45
  function cloneOperation(op) {
@@ -1404,7 +231,7 @@ var require_libc = __commonJS({
1404
231
 
1405
232
  // src/native-binding.ts
1406
233
  import * as fs from "fs";
1407
- import { createRequire as createRequire2 } from "module";
234
+ import { createRequire } from "module";
1408
235
  import path2 from "path";
1409
236
  import { fileURLToPath as fileURLToPath2 } from "url";
1410
237
  function packageRoot() {
@@ -1448,7 +275,7 @@ function nativePackageName(platform = process.platform, arch = process.arch, opt
1448
275
  function loadNative() {
1449
276
  const target = nativeTargetId();
1450
277
  const bindingPath = nativeBindingPath();
1451
- const require2 = createRequire2(import.meta.url);
278
+ const require2 = createRequire(import.meta.url);
1452
279
  if (fs.existsSync(bindingPath)) return require2(bindingPath);
1453
280
  const packageName = nativePackageName();
1454
281
  if (!packageName) {
@@ -1484,22 +311,192 @@ var init_native_binding = __esm({
1484
311
  }
1485
312
  });
1486
313
 
314
+ // src/image-builds.ts
315
+ import path3 from "path";
316
+ import os from "os";
317
+ import { existsSync as existsSync2, mkdtempSync, rmSync } from "fs";
318
+ function camelize(key) {
319
+ return key.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
320
+ }
321
+ function toImageBuildError(error) {
322
+ if (!(error instanceof Error)) return error;
323
+ let payload;
324
+ try {
325
+ payload = JSON.parse(error.message);
326
+ } catch {
327
+ return error;
328
+ }
329
+ if (!payload || payload.category !== "image_build") return error;
330
+ const details = {};
331
+ for (const [key, value] of Object.entries(payload)) {
332
+ if (key === "category") continue;
333
+ details[camelize(key)] = value;
334
+ }
335
+ const typed = details;
336
+ switch (typed.code) {
337
+ case "not_found":
338
+ return new ImageBuildNotFoundError(typed);
339
+ case "image_build_in_progress":
340
+ return new ImageBuildInProgressError(typed);
341
+ case "failed":
342
+ return new ImageBuildFailedError(typed);
343
+ case "cancelled":
344
+ return new ImageBuildCancelledError(typed);
345
+ case "timeout":
346
+ return new ImageBuildTimeoutError(typed);
347
+ case "interrupted":
348
+ return new ImageBuildInterruptedError(typed);
349
+ default:
350
+ return new ImageBuildError(typed);
351
+ }
352
+ }
353
+ function camelizeRecord(value) {
354
+ const out = {};
355
+ for (const [key, inner] of Object.entries(value)) out[camelize(key)] = inner;
356
+ return out;
357
+ }
358
+ function parseBuildInfo(raw) {
359
+ const camel = camelizeRecord(raw);
360
+ const result = raw.result && typeof raw.result === "object" ? camelizeRecord(raw.result) : null;
361
+ return {
362
+ buildId: String(raw.build_id ?? ""),
363
+ clientRequestId: camel.clientRequestId ?? null,
364
+ kind: String(raw.kind ?? ""),
365
+ name: raw.name ?? null,
366
+ status: String(raw.status ?? ""),
367
+ phase: raw.phase ?? null,
368
+ attemptNo: Number(raw.attempt_no ?? 0),
369
+ builderSandboxId: camel.builderSandboxId ?? null,
370
+ error: raw.error ?? null,
371
+ result,
372
+ operationDeadlineMs: camel.operationDeadlineMs ?? null,
373
+ createdAtMs: camel.createdAtMs ?? null,
374
+ updatedAtMs: camel.updatedAtMs ?? null,
375
+ raw
376
+ };
377
+ }
378
+ async function __runWithInterrupt(signal, run) {
379
+ const binding = __imageBuildInternals.loadNativeBinding();
380
+ if (signal === void 0) {
381
+ try {
382
+ return await run(void 0);
383
+ } catch (error) {
384
+ throw toImageBuildError(error);
385
+ }
386
+ }
387
+ const interruptId = binding.createImageBuildInterrupt();
388
+ const onAbort = () => binding.triggerImageBuildInterrupt(interruptId);
389
+ if (signal.aborted) onAbort();
390
+ else signal.addEventListener("abort", onAbort, { once: true });
391
+ try {
392
+ return await run(interruptId);
393
+ } catch (error) {
394
+ throw toImageBuildError(error);
395
+ } finally {
396
+ signal.removeEventListener("abort", onAbort);
397
+ binding.releaseImageBuildInterrupt(interruptId);
398
+ }
399
+ }
400
+ var ImageBuildError, ImageBuildNotFoundError, ImageBuildInProgressError, ImageBuildFailedError, ImageBuildCancelledError, ImageBuildTimeoutError, ImageBuildInterruptedError;
401
+ var init_image_builds = __esm({
402
+ "src/image-builds.ts"() {
403
+ "use strict";
404
+ init_esm_shims();
405
+ init_image();
406
+ init_sandbox_image();
407
+ ImageBuildError = class extends Error {
408
+ code;
409
+ buildId;
410
+ clientRequestId;
411
+ details;
412
+ constructor(details) {
413
+ super(details.message);
414
+ this.name = "ImageBuildError";
415
+ this.code = details.code;
416
+ this.details = details;
417
+ if (details.buildId) this.buildId = details.buildId;
418
+ if (details.clientRequestId) this.clientRequestId = details.clientRequestId;
419
+ }
420
+ };
421
+ ImageBuildNotFoundError = class extends ImageBuildError {
422
+ constructor(details) {
423
+ super(details);
424
+ this.name = "ImageBuildNotFoundError";
425
+ }
426
+ };
427
+ ImageBuildInProgressError = class extends ImageBuildError {
428
+ imageName;
429
+ activeBuildId;
430
+ activeKind;
431
+ activeStatus;
432
+ constructor(details) {
433
+ super(details);
434
+ this.name = "ImageBuildInProgressError";
435
+ if (details.imageName) this.imageName = details.imageName;
436
+ if (details.activeBuildId) this.activeBuildId = details.activeBuildId;
437
+ if (details.activeKind) this.activeKind = details.activeKind;
438
+ if (details.activeStatus) this.activeStatus = details.activeStatus;
439
+ }
440
+ };
441
+ ImageBuildFailedError = class extends ImageBuildError {
442
+ error;
443
+ info;
444
+ constructor(details) {
445
+ super(details);
446
+ this.name = "ImageBuildFailedError";
447
+ this.error = details.error ?? "no error recorded";
448
+ if (details.info) this.info = parseBuildInfo(details.info);
449
+ }
450
+ };
451
+ ImageBuildCancelledError = class extends ImageBuildError {
452
+ info;
453
+ constructor(details) {
454
+ super(details);
455
+ this.name = "ImageBuildCancelledError";
456
+ if (details.info) this.info = parseBuildInfo(details.info);
457
+ }
458
+ };
459
+ ImageBuildTimeoutError = class extends ImageBuildError {
460
+ constructor(details) {
461
+ super(details);
462
+ this.name = "ImageBuildTimeoutError";
463
+ }
464
+ };
465
+ ImageBuildInterruptedError = class extends ImageBuildError {
466
+ outcome;
467
+ confirmed;
468
+ result;
469
+ constructor(details) {
470
+ super(details);
471
+ this.name = "ImageBuildInterruptedError";
472
+ this.outcome = details.outcome ?? "unconfirmed";
473
+ this.confirmed = details.confirmed === true;
474
+ if (details.result) this.result = details.result;
475
+ }
476
+ };
477
+ }
478
+ });
479
+
1487
480
  // src/sandbox-image.ts
1488
481
  var sandbox_image_exports = {};
1489
482
  __export(sandbox_image_exports, {
483
+ __imageBuildInternals: () => __imageBuildInternals,
1490
484
  __setNativeBindingForTest: () => __setNativeBindingForTest,
1491
485
  buildContextFromEnv: () => buildContextFromEnv,
1492
486
  createSandboxImage: () => createSandboxImage,
1493
487
  deleteSandboxImage: () => deleteSandboxImage,
488
+ deleteSandboxImageWithCredentials: () => deleteSandboxImageWithCredentials,
1494
489
  findSandboxImageByName: () => findSandboxImageByName,
490
+ findSandboxImageByNameWithCredentials: () => findSandboxImageByNameWithCredentials,
1495
491
  importSandboxImage: () => importSandboxImage,
1496
492
  listSandboxImages: () => listSandboxImages,
493
+ listSandboxImagesWithCredentials: () => listSandboxImagesWithCredentials,
1497
494
  runCreateSandboxImageCli: () => runCreateSandboxImageCli,
1498
495
  runImportSandboxImageCli: () => runImportSandboxImageCli
1499
496
  });
1500
- import path3 from "path";
1501
- import os from "os";
1502
- import { existsSync as existsSync2, mkdtempSync, rmSync } from "fs";
497
+ import path4 from "path";
498
+ import os2 from "os";
499
+ import { existsSync as existsSync3, mkdtempSync as mkdtempSync2, rmSync as rmSync2 } from "fs";
1503
500
  import { parseArgs } from "util";
1504
501
  function loadNativeBinding() {
1505
502
  if (cachedNativeBinding) return cachedNativeBinding;
@@ -1533,9 +530,9 @@ function buildContextFromEnv() {
1533
530
  };
1534
531
  }
1535
532
  function defaultRegisteredName(dockerfilePath) {
1536
- const parsed = path3.parse(dockerfilePath);
533
+ const parsed = path4.parse(dockerfilePath);
1537
534
  if (parsed.name.toLowerCase() === "dockerfile") {
1538
- const parentName = path3.basename(path3.dirname(dockerfilePath)).trim();
535
+ const parentName = path4.basename(path4.dirname(dockerfilePath)).trim();
1539
536
  return parentName || "sandbox-image";
1540
537
  }
1541
538
  return parsed.name || "sandbox-image";
@@ -1571,6 +568,15 @@ function eventToEmitDict(event) {
1571
568
  message: event.message
1572
569
  };
1573
570
  if (event.stream != null) out.stream = event.stream;
571
+ if (event.buildId != null) out.build_id = event.buildId;
572
+ if (event.clientRequestId !== void 0 && event.eventType !== "status") {
573
+ out.client_request_id = event.clientRequestId;
574
+ }
575
+ if (event.status != null) out.status = event.status;
576
+ if (event.phase !== void 0 && event.eventType.startsWith("build_")) out.phase = event.phase;
577
+ if (event.attempt != null) out.attempt = event.attempt;
578
+ if (event.outcome != null) out.outcome = event.outcome;
579
+ if (event.confirmed != null) out.confirmed = event.confirmed;
1574
580
  return out;
1575
581
  }
1576
582
  function runOpMountsContext(op) {
@@ -1625,24 +631,24 @@ async function createSandboxImage(source, options = {}, deps = {}) {
1625
631
  }
1626
632
  let resolvedContext;
1627
633
  if (options.contextDir != null) {
1628
- resolvedContext = path3.resolve(options.contextDir);
634
+ resolvedContext = path4.resolve(options.contextDir);
1629
635
  } else if (imageRequiresContext(source)) {
1630
636
  throw new Error(
1631
637
  "This image reads files from the host (via COPY/ADD or a RUN bind mount), so it needs a build context. Pass `contextDir` pointing at the directory that contains those sources; they resolve relative to it, like `docker build <contextDir>`."
1632
638
  );
1633
639
  } else {
1634
- tempContextDir = mkdtempSync(path3.join(os.tmpdir(), "tl-build-context-"));
640
+ tempContextDir = mkdtempSync2(path4.join(os2.tmpdir(), "tl-build-context-"));
1635
641
  resolvedContext = tempContextDir;
1636
642
  }
1637
- dockerfilePath = path3.join(resolvedContext, "Dockerfile");
643
+ dockerfilePath = path4.join(resolvedContext, "Dockerfile");
1638
644
  let text = dockerfileContent(source);
1639
645
  if (!text.endsWith("\n")) text += "\n";
1640
646
  dockerfileText = text;
1641
647
  nativeContextDir = resolvedContext;
1642
648
  effectiveName = options.registeredName ?? source.name;
1643
649
  } else if (typeof source === "string") {
1644
- const resolvedPath = path3.resolve(source);
1645
- if (!existsSync2(resolvedPath)) {
650
+ const resolvedPath = path4.resolve(source);
651
+ if (!existsSync3(resolvedPath)) {
1646
652
  throw new Error(`Dockerfile not found: ${source}`);
1647
653
  }
1648
654
  dockerfilePath = resolvedPath;
@@ -1672,38 +678,47 @@ async function createSandboxImage(source, options = {}, deps = {}) {
1672
678
  deps._allowPat ? "Missing TENSORLAKE_API_KEY or TENSORLAKE_PAT credentials." : "Missing TENSORLAKE_API_KEY credentials."
1673
679
  );
1674
680
  }
681
+ if (options.signal !== void 0 && !options.cas) {
682
+ throw new Error(
683
+ "signal is only supported for CAS image builds (cas: true); a legacy build has no Image Service build operation to cancel"
684
+ );
685
+ }
1675
686
  emit({ type: "status", message: `Building image '${effectiveName}'...` });
1676
687
  const binding = loadNativeBinding();
1677
688
  let emitError;
1678
- const resultJson = await binding.buildSandboxImage(
1679
- {
1680
- apiUrl: context.apiUrl,
1681
- bearerToken,
1682
- dockerfilePath,
1683
- registeredName: effectiveName,
1684
- diskMb: options.diskMb,
1685
- builderDiskMb: options.builderDiskMb,
1686
- cpus: options.cpus,
1687
- memoryMb: options.memoryMb,
1688
- isPublic: options.isPublic ?? false,
1689
- organizationId: usePat ? context.organizationId : void 0,
1690
- projectId: usePat ? context.projectId : void 0,
1691
- namespace: context.namespace,
1692
- useScopeHeaders: usePat,
1693
- userAgent: void 0,
1694
- dockerCompat: options.dockerCompat ?? false,
1695
- dockerConfigJson: options.dockerConfigJson,
1696
- dockerfileText,
1697
- contextDir: nativeContextDir
1698
- },
1699
- (event) => {
1700
- try {
1701
- emit(eventToEmitDict(event));
1702
- } catch (error) {
1703
- emitError ??= error;
1704
- }
689
+ const nativeOptions = {
690
+ apiUrl: context.apiUrl,
691
+ bearerToken,
692
+ dockerfilePath,
693
+ registeredName: effectiveName,
694
+ diskMb: options.diskMb,
695
+ builderDiskMb: options.builderDiskMb,
696
+ cpus: options.cpus,
697
+ memoryMb: options.memoryMb,
698
+ isPublic: options.isPublic ?? false,
699
+ organizationId: usePat ? context.organizationId : void 0,
700
+ projectId: usePat ? context.projectId : void 0,
701
+ namespace: context.namespace,
702
+ useScopeHeaders: usePat,
703
+ userAgent: void 0,
704
+ dockerCompat: options.dockerCompat ?? false,
705
+ dockerConfigJson: options.dockerConfigJson,
706
+ dockerfileText,
707
+ contextDir: nativeContextDir,
708
+ cas: options.cas ?? false,
709
+ buildArgs: options.buildArgs
710
+ };
711
+ const forward = (event) => {
712
+ try {
713
+ emit(eventToEmitDict(event));
714
+ } catch (error) {
715
+ emitError ??= error;
1705
716
  }
1706
- );
717
+ };
718
+ const resultJson = options.cas ? await __runWithInterrupt(
719
+ options.signal,
720
+ (interruptId) => binding.buildSandboxImage(nativeOptions, forward, interruptId)
721
+ ) : await binding.buildSandboxImage(nativeOptions, forward);
1707
722
  if (emitError != null) {
1708
723
  throw emitError;
1709
724
  }
@@ -1720,7 +735,7 @@ async function createSandboxImage(source, options = {}, deps = {}) {
1720
735
  return result;
1721
736
  } finally {
1722
737
  if (tempContextDir != null) {
1723
- rmSync(tempContextDir, { recursive: true, force: true });
738
+ rmSync2(tempContextDir, { recursive: true, force: true });
1724
739
  }
1725
740
  }
1726
741
  }
@@ -1749,39 +764,47 @@ async function importSandboxImage(imageReference, options = {}, deps = {}) {
1749
764
  deps._allowPat ? "Missing TENSORLAKE_API_KEY or TENSORLAKE_PAT credentials." : "Missing TENSORLAKE_API_KEY credentials."
1750
765
  );
1751
766
  }
767
+ if (options.signal !== void 0 && !options.cas) {
768
+ throw new Error(
769
+ "signal is only supported for CAS image imports (cas: true); a legacy import has no Image Service build operation to cancel"
770
+ );
771
+ }
1752
772
  emit({
1753
773
  type: "status",
1754
774
  message: `Importing image '${reference}' as '${effectiveName}'...`
1755
775
  });
1756
776
  const binding = loadNativeBinding();
1757
777
  let emitError;
1758
- const resultJson = await binding.importSandboxImage(
1759
- {
1760
- apiUrl: context.apiUrl,
1761
- bearerToken,
1762
- imageReference: reference,
1763
- registeredName: effectiveName,
1764
- diskMb: options.diskMb,
1765
- builderDiskMb: options.builderDiskMb,
1766
- cpus: options.cpus,
1767
- memoryMb: options.memoryMb,
1768
- isPublic: options.isPublic ?? false,
1769
- organizationId: usePat ? context.organizationId : void 0,
1770
- projectId: usePat ? context.projectId : void 0,
1771
- namespace: context.namespace,
1772
- useScopeHeaders: usePat,
1773
- userAgent: void 0,
1774
- dockerCompat: options.dockerCompat ?? false,
1775
- dockerConfigJson: options.dockerConfigJson
1776
- },
1777
- (event) => {
1778
- try {
1779
- emit(eventToEmitDict(event));
1780
- } catch (error) {
1781
- emitError ??= error;
1782
- }
778
+ const nativeOptions = {
779
+ apiUrl: context.apiUrl,
780
+ bearerToken,
781
+ imageReference: reference,
782
+ registeredName: effectiveName,
783
+ diskMb: options.diskMb,
784
+ builderDiskMb: options.builderDiskMb,
785
+ cpus: options.cpus,
786
+ memoryMb: options.memoryMb,
787
+ isPublic: options.isPublic ?? false,
788
+ organizationId: usePat ? context.organizationId : void 0,
789
+ projectId: usePat ? context.projectId : void 0,
790
+ namespace: context.namespace,
791
+ useScopeHeaders: usePat,
792
+ userAgent: void 0,
793
+ dockerCompat: options.dockerCompat ?? false,
794
+ dockerConfigJson: options.dockerConfigJson,
795
+ cas: options.cas ?? false
796
+ };
797
+ const forward = (event) => {
798
+ try {
799
+ emit(eventToEmitDict(event));
800
+ } catch (error) {
801
+ emitError ??= error;
1783
802
  }
1784
- );
803
+ };
804
+ const resultJson = options.cas ? await __runWithInterrupt(
805
+ options.signal,
806
+ (interruptId) => binding.importSandboxImage(nativeOptions, forward, interruptId)
807
+ ) : await binding.importSandboxImage(nativeOptions, forward);
1785
808
  if (emitError != null) {
1786
809
  throw emitError;
1787
810
  }
@@ -1797,10 +820,7 @@ async function importSandboxImage(imageReference, options = {}, deps = {}) {
1797
820
  emit({ type: "done" });
1798
821
  return result;
1799
822
  }
1800
- async function deleteSandboxImage(imageName) {
1801
- if (typeof imageName !== "string" || imageName.length === 0) {
1802
- throw new TypeError("imageName must be a non-empty string");
1803
- }
823
+ function catalogOptionsFromEnv() {
1804
824
  const context = buildContextFromEnv();
1805
825
  const bearerToken = context.apiKey;
1806
826
  if (!bearerToken) {
@@ -1811,63 +831,73 @@ async function deleteSandboxImage(imageName) {
1811
831
  }
1812
832
  throw new Error("Missing TENSORLAKE_API_KEY credentials.");
1813
833
  }
1814
- const client = new CloudClient({
1815
- apiUrl: context.apiUrl,
1816
- apiKey: bearerToken,
1817
- namespace: context.namespace
1818
- });
1819
- try {
1820
- await client.deleteSandboxImage(imageName);
1821
- } finally {
1822
- client.close();
1823
- }
834
+ return { apiUrl: context.apiUrl, bearerToken, useScopeHeaders: false };
1824
835
  }
1825
- async function findSandboxImageByName(imageName) {
1826
- if (typeof imageName !== "string" || imageName.length === 0) {
1827
- throw new TypeError("imageName must be a non-empty string");
1828
- }
836
+ function catalogOptionsFromCredentials(credentials) {
1829
837
  const context = buildContextFromEnv();
1830
- const bearerToken = context.apiKey;
838
+ const bearerToken = credentials.apiKey ?? context.apiKey;
1831
839
  if (!bearerToken) {
1832
- if (context.personalAccessToken) {
1833
- throw new Error(
1834
- "Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only."
1835
- );
1836
- }
1837
840
  throw new Error("Missing TENSORLAKE_API_KEY credentials.");
1838
841
  }
1839
- const client = new CloudClient({
1840
- apiUrl: context.apiUrl,
1841
- apiKey: bearerToken,
1842
- namespace: context.namespace
1843
- });
1844
- try {
1845
- return await client.findSandboxImageByName(imageName);
1846
- } finally {
1847
- client.close();
842
+ const { organizationId, projectId } = credentials;
843
+ if (organizationId === void 0 !== (projectId === void 0)) {
844
+ throw new TypeError("organizationId and projectId must be given together");
1848
845
  }
846
+ return {
847
+ apiUrl: credentials.apiUrl ?? context.apiUrl,
848
+ bearerToken,
849
+ organizationId,
850
+ projectId,
851
+ useScopeHeaders: organizationId !== void 0
852
+ };
1849
853
  }
1850
- async function listSandboxImages() {
1851
- const context = buildContextFromEnv();
1852
- const bearerToken = context.apiKey;
1853
- if (!bearerToken) {
1854
- if (context.personalAccessToken) {
1855
- throw new Error(
1856
- "Sandbox image SDKs require TENSORLAKE_API_KEY. Personal access tokens are CLI-only."
1857
- );
1858
- }
1859
- throw new Error("Missing TENSORLAKE_API_KEY credentials.");
854
+ function parseTemplate(json) {
855
+ return JSON.parse(json);
856
+ }
857
+ async function deleteSandboxImage(imageName) {
858
+ if (typeof imageName !== "string" || imageName.length === 0) {
859
+ throw new TypeError("imageName must be a non-empty string");
1860
860
  }
1861
- const client = new CloudClient({
1862
- apiUrl: context.apiUrl,
1863
- apiKey: bearerToken,
1864
- namespace: context.namespace
1865
- });
1866
- try {
1867
- return await client.listSandboxImages();
1868
- } finally {
1869
- client.close();
861
+ await loadNativeBinding().deleteSandboxImage(catalogOptionsFromEnv(), imageName);
862
+ }
863
+ async function deleteSandboxImageWithCredentials(credentials, imageName) {
864
+ if (typeof imageName !== "string" || imageName.length === 0) {
865
+ throw new TypeError("imageName must be a non-empty string");
1870
866
  }
867
+ await loadNativeBinding().deleteSandboxImage(
868
+ catalogOptionsFromCredentials(credentials),
869
+ imageName
870
+ );
871
+ }
872
+ async function findSandboxImageByName(imageName) {
873
+ if (typeof imageName !== "string" || imageName.length === 0) {
874
+ throw new TypeError("imageName must be a non-empty string");
875
+ }
876
+ const json = await loadNativeBinding().findSandboxImage(
877
+ catalogOptionsFromEnv(),
878
+ imageName
879
+ );
880
+ return json == null ? null : parseTemplate(json);
881
+ }
882
+ async function findSandboxImageByNameWithCredentials(credentials, imageName) {
883
+ if (typeof imageName !== "string" || imageName.length === 0) {
884
+ throw new TypeError("imageName must be a non-empty string");
885
+ }
886
+ const json = await loadNativeBinding().findSandboxImage(
887
+ catalogOptionsFromCredentials(credentials),
888
+ imageName
889
+ );
890
+ return json == null ? null : parseTemplate(json);
891
+ }
892
+ async function listSandboxImages() {
893
+ const json = await loadNativeBinding().listSandboxImages(catalogOptionsFromEnv());
894
+ return JSON.parse(json);
895
+ }
896
+ async function listSandboxImagesWithCredentials(credentials) {
897
+ const json = await loadNativeBinding().listSandboxImages(
898
+ catalogOptionsFromCredentials(credentials)
899
+ );
900
+ return JSON.parse(json);
1871
901
  }
1872
902
  async function runCreateSandboxImageCli(argv = process.argv.slice(2)) {
1873
903
  const parsed = parseArgs({
@@ -1977,25 +1007,39 @@ async function runImportSandboxImageCli(argv = process.argv.slice(2)) {
1977
1007
  { emit: ndjsonStdoutEmit, _allowPat: true }
1978
1008
  );
1979
1009
  }
1980
- var cachedNativeBinding, cachedNativeBindingError, DEFAULT_IMAGE_NAME2;
1010
+ var cachedNativeBinding, cachedNativeBindingError, DEFAULT_IMAGE_NAME2, __imageBuildInternals;
1981
1011
  var init_sandbox_image = __esm({
1982
1012
  "src/sandbox-image.ts"() {
1983
1013
  init_esm_shims();
1984
- init_cloud_client();
1985
1014
  init_image();
1986
1015
  init_native_binding();
1016
+ init_image_builds();
1987
1017
  DEFAULT_IMAGE_NAME2 = "default";
1018
+ __imageBuildInternals = {
1019
+ loadNativeBinding: () => loadNativeBinding(),
1020
+ buildContextFromEnv: () => buildContextFromEnv(),
1021
+ stderrEmit: (event) => stderrEmit(event),
1022
+ noopEmit: (event) => noopEmit(event),
1023
+ eventToEmitDict: (event) => eventToEmitDict(event),
1024
+ imageRequiresContext: (image) => imageRequiresContext(image),
1025
+ defaultRegisteredName: (dockerfilePath) => defaultRegisteredName(dockerfilePath),
1026
+ defaultRegisteredNameFromImage: (reference) => defaultRegisteredNameFromImage(reference)
1027
+ };
1988
1028
  }
1989
1029
  });
1990
1030
  init_sandbox_image();
1991
1031
  export {
1032
+ __imageBuildInternals,
1992
1033
  __setNativeBindingForTest,
1993
1034
  buildContextFromEnv,
1994
1035
  createSandboxImage,
1995
1036
  deleteSandboxImage,
1037
+ deleteSandboxImageWithCredentials,
1996
1038
  findSandboxImageByName,
1039
+ findSandboxImageByNameWithCredentials,
1997
1040
  importSandboxImage,
1998
1041
  listSandboxImages,
1042
+ listSandboxImagesWithCredentials,
1999
1043
  runCreateSandboxImageCli,
2000
1044
  runImportSandboxImageCli
2001
1045
  };