tensorlake 0.5.131 → 0.5.133

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 (50) hide show
  1. package/README.md +27 -0
  2. package/dist/applications/index.cjs +492 -708
  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 +493 -713
  7. package/dist/applications/index.js.map +1 -1
  8. package/dist/function-agent/main.cjs +5 -2
  9. package/dist/function-agent/main.cjs.map +1 -1
  10. package/dist/function-agent/main.js +6 -3
  11. package/dist/function-agent/main.js.map +1 -1
  12. package/dist/function-executor/main.cjs +6 -3
  13. package/dist/function-executor/main.cjs.map +1 -1
  14. package/dist/function-executor/main.js +7 -4
  15. package/dist/function-executor/main.js.map +1 -1
  16. package/dist/index.cjs +121 -418
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +8 -22
  19. package/dist/index.d.ts +8 -22
  20. package/dist/index.js +122 -423
  21. package/dist/index.js.map +1 -1
  22. package/dist/native-worker.cjs +1 -0
  23. package/dist/native-worker.cjs.map +1 -1
  24. package/dist/native-worker.js +1 -0
  25. package/dist/native-worker.js.map +1 -1
  26. package/dist/{remote-DRCCuRth.d.cts → remote-D95Y6Czr.d.cts} +1 -1
  27. package/dist/{remote-0dzBqScB.d.ts → remote-omwTzbfj.d.ts} +1 -1
  28. package/dist/{sandbox-image-Bf5bcxtO.d.cts → sandbox-image-ChzWDeZy.d.cts} +2 -0
  29. package/dist/{sandbox-image-Bf5bcxtO.d.ts → sandbox-image-ChzWDeZy.d.ts} +2 -0
  30. package/dist/sandbox-image.cjs +476 -453
  31. package/dist/sandbox-image.cjs.map +1 -1
  32. package/dist/sandbox-image.d.cts +1 -1
  33. package/dist/sandbox-image.d.ts +1 -1
  34. package/dist/sandbox-image.js +475 -456
  35. package/dist/sandbox-image.js.map +1 -1
  36. package/package.json +8 -8
  37. package/runtime/function-executor/manifest.json +14 -14
  38. package/runtime/function-executor/package/dist/function-executor/main.js +7 -4
  39. package/runtime/function-executor/package/dist/function-executor/main.js.map +1 -1
  40. package/runtime/function-executor/package/dist/native-worker.cjs +1 -0
  41. package/runtime/function-executor/package/dist/native-worker.cjs.map +1 -1
  42. package/runtime/function-executor/package/npm-shrinkwrap.json +2 -12
  43. package/runtime/function-executor/package/package.json +1 -2
  44. package/runtime/typescript-function-runner/manifest.json +13 -13
  45. package/runtime/typescript-function-runner/package/dist/function-agent/main.js +6 -3
  46. package/runtime/typescript-function-runner/package/dist/function-agent/main.js.map +1 -1
  47. package/runtime/typescript-function-runner/package/dist/native-worker.cjs +1 -0
  48. package/runtime/typescript-function-runner/package/dist/native-worker.cjs.map +1 -1
  49. package/runtime/typescript-function-runner/package/npm-shrinkwrap.json +20 -29
  50. package/runtime/typescript-function-runner/package/package.json +7 -7
package/dist/index.js CHANGED
@@ -41,12 +41,12 @@ var init_esm_shims = __esm({
41
41
  });
42
42
 
43
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, RETRYABLE_STATUS_CODES;
44
+ var SDK_VERSION, API_URL, API_KEY, NAMESPACE, SANDBOX_PROXY_URL, DEFAULT_HTTP_TIMEOUT_MS, MAX_RETRIES, RETRY_BACKOFF_MS;
45
45
  var init_defaults = __esm({
46
46
  "src/defaults.ts"() {
47
47
  "use strict";
48
48
  init_esm_shims();
49
- SDK_VERSION = "0.5.131";
49
+ SDK_VERSION = "0.5.133";
50
50
  API_URL = process.env.TENSORLAKE_API_URL ?? "https://api.tensorlake.ai";
51
51
  API_KEY = process.env.TENSORLAKE_API_KEY ?? void 0;
52
52
  NAMESPACE = process.env.INDEXIFY_NAMESPACE ?? "default";
@@ -54,33 +54,10 @@ var init_defaults = __esm({
54
54
  DEFAULT_HTTP_TIMEOUT_MS = 3e5;
55
55
  MAX_RETRIES = 3;
56
56
  RETRY_BACKOFF_MS = 500;
57
- RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
58
57
  }
59
58
  });
60
59
 
61
60
  // src/errors.ts
62
- function describeError(err) {
63
- const parts = [];
64
- const seen = /* @__PURE__ */ new Set();
65
- let current = err;
66
- for (let depth = 0; depth < 6; depth++) {
67
- if (current == null || typeof current !== "object" || seen.has(current)) {
68
- break;
69
- }
70
- seen.add(current);
71
- const e = current;
72
- const message = typeof e.message === "string" ? e.message.trim() : "";
73
- const code = typeof e.code === "string" ? e.code : void 0;
74
- let segment = message;
75
- if (code && (!message || !message.includes(code))) {
76
- segment = segment ? `${segment} (${code})` : code;
77
- }
78
- if (segment && !parts.includes(segment)) parts.push(segment);
79
- current = e.cause;
80
- }
81
- if (parts.length > 0) return parts.join(": ");
82
- return err instanceof Error ? err.message : String(err);
83
- }
84
61
  function formatErrorDetails(errorDetails) {
85
62
  if (errorDetails == null) return void 0;
86
63
  if (typeof errorDetails === "string") {
@@ -280,9 +257,14 @@ var init_url = __esm({
280
257
 
281
258
  // src/native-worker-client.ts
282
259
  import { createRequire } from "module";
283
- import { SHARE_ENV, Worker } from "worker_threads";
260
+ import { Worker } from "worker_threads";
284
261
  function createWorkerBinding(runtime) {
285
262
  return {
263
+ NativeCloudClient: class {
264
+ constructor(...args) {
265
+ return runtime.handle("NativeCloudClient", args);
266
+ }
267
+ },
286
268
  NativeSandboxClient: class {
287
269
  constructor(...args) {
288
270
  return runtime.handle("NativeSandboxClient", args);
@@ -398,7 +380,10 @@ var init_native_worker_client = __esm({
398
380
  getWorker() {
399
381
  if (this.worker) return this.worker;
400
382
  const worker = new Worker(this.workerPath(), {
401
- env: SHARE_ENV,
383
+ // The bundled worker needs no application loaders or telemetry preloads.
384
+ // NODE_OPTIONS is parsed independently of execArgv by Node.
385
+ execArgv: [],
386
+ env: { ...process.env, NODE_OPTIONS: "" },
402
387
  name: "tensorlake-native"
403
388
  });
404
389
  this.worker = worker;
@@ -472,7 +457,7 @@ var init_native_worker_client = __esm({
472
457
  }
473
458
  };
474
459
  runtimeKey = /* @__PURE__ */ Symbol.for(
475
- `tensorlake.native.worker.${false ? "source" : "0.5.131"}.v1`
460
+ `tensorlake.native.worker.${false ? "source" : "0.5.133"}.v1`
476
461
  );
477
462
  runtimes = globalThis;
478
463
  }
@@ -5294,374 +5279,87 @@ var init_client = __esm({
5294
5279
  }
5295
5280
  });
5296
5281
 
5297
- // src/http.ts
5298
- import {
5299
- Agent,
5300
- fetch as undiciFetch,
5301
- setGlobalDispatcher
5302
- } from "undici";
5303
- function withTraceId(value, traceId) {
5304
- if (value == null) {
5305
- return { traceId };
5306
- }
5307
- return Object.assign(value, { traceId });
5308
- }
5309
- function hasHeader(headers, name) {
5310
- const lowered = name.toLowerCase();
5311
- return Object.keys(headers).some((key) => key.toLowerCase() === lowered);
5312
- }
5313
- function normalizeRequestBody(body) {
5314
- if (body == null) {
5315
- return void 0;
5316
- }
5317
- if (body instanceof Uint8Array) {
5318
- return Uint8Array.from(body).buffer;
5319
- }
5320
- return body;
5321
- }
5322
- function stripPathPayload(path4) {
5323
- const queryStart = path4.search(/[?#]/);
5324
- return queryStart === -1 ? path4 : path4.slice(0, queryStart);
5325
- }
5326
- function throwMappedError(status, body, path4) {
5327
- let message = body;
5328
- try {
5329
- const parsed = JSON.parse(body);
5330
- if (parsed.message) message = parsed.message;
5331
- else if (parsed.error) message = parsed.error;
5332
- } catch {
5333
- }
5334
- if (status === 404) {
5335
- if (path4.includes("sandbox-pools") || path4.includes("pools")) {
5336
- const match = path4.match(/sandbox-pools\/([^/]+)/);
5337
- if (match) throw new PoolNotFoundError(match[1]);
5338
- }
5339
- if (path4.includes("sandboxes")) {
5340
- const match = path4.match(/sandboxes\/([^/]+)/);
5341
- if (match) throw new SandboxNotFoundError(match[1]);
5342
- }
5343
- throw new RemoteAPIError(404, message);
5344
- }
5345
- if (status === 409) {
5346
- if (path4.includes("sandbox-pools") || path4.includes("pools")) {
5347
- const match = path4.match(/sandbox-pools\/([^/]+)/);
5348
- if (match) throw new PoolInUseError(match[1], message);
5349
- }
5350
- }
5351
- throw new RemoteAPIError(status, message);
5352
- }
5353
- function anySignal(signals) {
5354
- const controller = new AbortController();
5355
- for (const signal of signals) {
5356
- if (signal.aborted) {
5357
- controller.abort(signal.reason);
5358
- return controller.signal;
5359
- }
5360
- signal.addEventListener("abort", () => controller.abort(signal.reason), {
5361
- once: true
5362
- });
5363
- }
5364
- return controller.signal;
5365
- }
5366
- function sleep3(ms) {
5367
- return new Promise((resolve2) => setTimeout(resolve2, ms));
5368
- }
5369
- var REQUEST_TIMEOUT_HEADER, HttpClient;
5370
- var init_http = __esm({
5371
- "src/http.ts"() {
5282
+ // src/native-cloud.ts
5283
+ async function serializeRequest(method, path4, options) {
5284
+ const headers = { ...options?.headers };
5285
+ let body = options?.body;
5286
+ if (options?.json !== void 0) {
5287
+ body = JSON.stringify(options.json);
5288
+ if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {
5289
+ headers["Content-Type"] = "application/json";
5290
+ }
5291
+ }
5292
+ const request = {
5293
+ method,
5294
+ path: path4,
5295
+ headersJson: JSON.stringify(headers),
5296
+ statusOnlyCodes: [...options?.statusOnlyCodes ?? []]
5297
+ };
5298
+ if (body instanceof FormData) {
5299
+ request.parts = [];
5300
+ for (const [name, value] of body.entries()) {
5301
+ 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" });
5302
+ }
5303
+ } else if (body !== void 0) {
5304
+ if (body instanceof Blob) request.body = Buffer.from(await body.arrayBuffer());
5305
+ else if (typeof body === "string") request.body = Buffer.from(body);
5306
+ else if (body instanceof ArrayBuffer) request.body = Buffer.from(new Uint8Array(body));
5307
+ else request.body = Buffer.from(body);
5308
+ }
5309
+ return request;
5310
+ }
5311
+ var NativeCloudTransport;
5312
+ var init_native_cloud = __esm({
5313
+ "src/native-cloud.ts"() {
5372
5314
  "use strict";
5373
5315
  init_esm_shims();
5374
- init_defaults();
5375
- init_errors();
5376
- init_sdk_timings();
5377
- REQUEST_TIMEOUT_HEADER = "X-Tensorlake-Request-Timeout-Ms";
5378
- setGlobalDispatcher(
5379
- new Agent({
5380
- keepAliveTimeout: 6e4,
5381
- allowH2: true
5382
- })
5383
- );
5384
- HttpClient = class _HttpClient {
5385
- baseUrl;
5386
- headers;
5387
- maxRetries;
5388
- retryBackoffMs;
5389
- timeoutMs;
5390
- abortController = null;
5316
+ init_native_sandbox();
5317
+ init_native_worker_client();
5318
+ NativeCloudTransport = class {
5391
5319
  constructor(options) {
5392
- const url = options.baseUrl;
5393
- this.baseUrl = url.endsWith("/") ? url.slice(0, -1) : url;
5394
- this.maxRetries = options.maxRetries ?? MAX_RETRIES;
5395
- this.retryBackoffMs = options.retryBackoffMs ?? RETRY_BACKOFF_MS;
5396
- this.timeoutMs = options.timeoutMs === void 0 ? DEFAULT_HTTP_TIMEOUT_MS : options.timeoutMs;
5397
- this.headers = {
5398
- "User-Agent": `tensorlake-typescript-sdk/${SDK_VERSION}`
5399
- };
5400
- if (this.timeoutMs != null) {
5401
- this.headers[REQUEST_TIMEOUT_HEADER] = String(this.timeoutMs);
5402
- }
5403
- if (options.apiKey) {
5404
- this.headers["Authorization"] = `Bearer ${options.apiKey}`;
5405
- }
5406
- if (options.organizationId) {
5407
- this.headers["X-Forwarded-Organization-Id"] = options.organizationId;
5408
- }
5409
- if (options.projectId) {
5410
- this.headers["X-Forwarded-Project-Id"] = options.projectId;
5411
- }
5412
- if (options.hostHeader) {
5413
- this.headers["Host"] = options.hostHeader;
5414
- }
5415
- if (options.sandboxIdHeader) {
5416
- this.headers["X-Tensorlake-Sandbox-Id"] = options.sandboxIdHeader;
5320
+ this.options = options;
5321
+ if (!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0 || options.maxRetries > 4294967295) {
5322
+ throw new RangeError("maxRetries must be a non-negative 32-bit integer");
5417
5323
  }
5418
- if (options.routingHint) {
5419
- this.headers["X-Tensorlake-Route-Hint"] = options.routingHint;
5324
+ if (!Number.isFinite(options.retryBackoffMs) || options.retryBackoffMs < 0) {
5325
+ throw new RangeError("retryBackoffMs must be a non-negative finite number");
5420
5326
  }
5421
5327
  }
5328
+ native;
5329
+ closed = false;
5330
+ client() {
5331
+ if (this.closed) throw new Error("Tensorlake native client is closed");
5332
+ if (this.native) return this.native;
5333
+ const ctor = loadNativeSandboxBinding().NativeCloudClient;
5334
+ if (!ctor) throw new Error("Native binding does not export NativeCloudClient; rebuild with 'npm run build:native'");
5335
+ return this.native = new ctor(JSON.stringify(this.options));
5336
+ }
5422
5337
  close() {
5423
- this.abortController?.abort();
5424
- this.abortController = null;
5425
- }
5426
- /** Make a JSON request, returning the parsed response body. */
5427
- async requestJson(method, path4, options) {
5428
- const response = await this.requestResponse(method, path4, {
5429
- json: options?.body,
5430
- headers: options?.headers,
5431
- signal: options?.signal,
5432
- retryableStatusCodes: options?.retryableStatusCodes,
5433
- allowedErrorStatusCodes: options?.allowedErrorStatusCodes,
5434
- allowHttpErrors: options?.allowHttpErrors
5435
- });
5436
- const text = await response.text();
5437
- const data = text ? JSON.parse(text) : void 0;
5438
- return withTraceId(data, response.traceId);
5439
- }
5440
- /** Make a request returning raw bytes. */
5441
- async requestBytes(method, path4, options) {
5442
- const headers = { ...options?.headers ?? {} };
5443
- if (options?.contentType) {
5444
- headers["Content-Type"] = options.contentType;
5445
- }
5446
- const response = await this.requestResponse(method, path4, {
5447
- body: options?.body,
5448
- headers,
5449
- signal: options?.signal
5450
- });
5451
- const buffer = await response.arrayBuffer();
5452
- return withTraceId(new Uint8Array(buffer), response.traceId);
5453
- }
5454
- /** Make a request and return the response body as an SSE stream. */
5455
- async requestStream(method, path4, options) {
5456
- const response = await this.requestResponse(method, path4, {
5457
- json: options?.json,
5458
- headers: { Accept: "text/event-stream" },
5459
- signal: options?.signal
5460
- });
5461
- if (!response.body) {
5462
- throw new RemoteAPIError(
5463
- response.status,
5464
- "No response body for SSE stream"
5465
- );
5466
- }
5467
- return withTraceId(response.body, response.traceId);
5338
+ this.closed = true;
5339
+ releaseNativeHandle(this.native ?? null);
5340
+ this.native = void 0;
5468
5341
  }
5469
- /** Make a request and return the raw Response. */
5470
5342
  async requestResponse(method, path4, options) {
5471
- const headers = {
5472
- ...this.headers,
5473
- ...options?.headers ?? {}
5474
- };
5475
- const hasJsonBody = options?.json !== void 0;
5476
- if (hasJsonBody && !hasHeader(headers, "Content-Type")) {
5477
- headers["Content-Type"] = "application/json";
5478
- }
5479
- const body = hasJsonBody ? JSON.stringify(options?.json) : normalizeRequestBody(options?.body);
5480
- const { response, traceId } = await this.doFetch(
5481
- method,
5482
- path4,
5483
- body,
5484
- headers,
5485
- options?.signal,
5486
- options?.allowHttpErrors ?? false,
5487
- options?.retryableStatusCodes ?? RETRYABLE_STATUS_CODES,
5488
- options?.allowedErrorStatusCodes ?? /* @__PURE__ */ new Set()
5489
- );
5490
- return withTraceId(response, traceId);
5491
- }
5492
- static makeTraceparent() {
5493
- const randomHex = (bytes) => Array.from(crypto.getRandomValues(new Uint8Array(bytes))).map((b) => b.toString(16).padStart(2, "0")).join("");
5494
- const traceId = randomHex(16);
5495
- const spanId = randomHex(8);
5496
- return { traceparent: `00-${traceId}-${spanId}-01`, traceId };
5497
- }
5498
- async doFetch(method, path4, body, headers, signal, allowHttpErrors = false, retryableStatusCodes = RETRYABLE_STATUS_CODES, allowedErrorStatusCodes = /* @__PURE__ */ new Set()) {
5499
- const url = `${this.baseUrl}${path4}`;
5500
- const { traceparent, traceId } = _HttpClient.makeTraceparent();
5501
- headers["traceparent"] = traceparent;
5502
- let lastError;
5503
- const operationStart = nowMs();
5504
- const timingPath = sdkTimingPayloadsEnabled() ? path4 : stripPathPayload(path4);
5505
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
5506
- if (attempt > 0) {
5507
- const delay = this.retryBackoffMs * Math.pow(2, attempt - 1);
5508
- logSdkTimingEvent("http.request", "retry_sleep_start", {
5509
- method,
5510
- path: timingPath,
5511
- attempt,
5512
- delay_ms: delay,
5513
- server_trace_id: traceId
5514
- });
5515
- await sleep3(delay);
5516
- }
5517
- this.abortController = new AbortController();
5518
- let timedOut = false;
5519
- const timeoutId = this.timeoutMs == null ? null : setTimeout(() => {
5520
- timedOut = true;
5521
- this.abortController?.abort();
5522
- }, this.timeoutMs);
5523
- const combinedSignal = signal ? anySignal([signal, this.abortController.signal]) : this.abortController.signal;
5524
- const attemptStart = nowMs();
5525
- try {
5526
- const response = await undiciFetch(url, {
5527
- method,
5528
- headers,
5529
- body,
5530
- signal: combinedSignal
5531
- });
5532
- if (timeoutId != null) clearTimeout(timeoutId);
5533
- logSdkTiming("http.request", "headers", attemptStart, {
5534
- method,
5535
- path: timingPath,
5536
- status: response.status,
5537
- attempt,
5538
- server_trace_id: traceId
5539
- });
5540
- if (response.ok) {
5541
- logSdkTiming("http.request", "complete", operationStart, {
5542
- method,
5543
- path: timingPath,
5544
- status: response.status,
5545
- attempts: attempt + 1,
5546
- server_trace_id: traceId
5547
- });
5548
- return { response, traceId };
5549
- }
5550
- if (retryableStatusCodes.has(response.status) && attempt < this.maxRetries) {
5551
- lastError = new RemoteAPIError(
5552
- response.status,
5553
- await response.text().catch(() => "")
5554
- );
5555
- logSdkTimingEvent("http.request", "retryable_status", {
5556
- method,
5557
- path: timingPath,
5558
- status: response.status,
5559
- attempt,
5560
- server_trace_id: traceId
5561
- });
5562
- continue;
5563
- }
5564
- if (allowHttpErrors || allowedErrorStatusCodes.has(response.status)) {
5565
- logSdkTiming("http.request", "complete", operationStart, {
5566
- method,
5567
- path: timingPath,
5568
- status: response.status,
5569
- attempts: attempt + 1,
5570
- server_trace_id: traceId
5571
- });
5572
- return { response, traceId };
5573
- }
5574
- const errorBody = await response.text().catch(() => "");
5575
- throwMappedError(response.status, errorBody, path4);
5576
- } catch (err) {
5577
- if (timeoutId != null) clearTimeout(timeoutId);
5578
- if (err instanceof RemoteAPIError || err instanceof SandboxNotFoundError || err instanceof PoolNotFoundError || err instanceof PoolInUseError) {
5579
- throw err;
5580
- }
5581
- if (signal?.aborted && !timedOut) {
5582
- throw new SandboxConnectionError("request aborted by caller", {
5583
- cause: err
5584
- });
5585
- }
5586
- lastError = err instanceof Error ? err : new Error(String(err));
5587
- logSdkTiming("http.request", "error", attemptStart, {
5588
- method,
5589
- path: timingPath,
5590
- attempt,
5591
- server_trace_id: traceId,
5592
- error: timedOut ? `request timed out after ${this.timeoutMs}ms` : describeError(err)
5593
- });
5594
- if (attempt >= this.maxRetries) {
5595
- const detail = timedOut ? `request timed out after ${this.timeoutMs}ms` : describeError(err);
5596
- throw new SandboxConnectionError(detail, { cause: err });
5597
- }
5598
- }
5599
- }
5600
- throw new SandboxConnectionError(
5601
- lastError ? describeError(lastError) : "request failed",
5602
- { cause: lastError }
5343
+ const request = await serializeRequest(method, path4, options);
5344
+ const raw = await callNative(() => this.client().request(request));
5345
+ const response = new Response(
5346
+ [204, 205, 304].includes(raw.status) ? null : Uint8Array.from(raw.data).buffer,
5347
+ { status: raw.status, headers: JSON.parse(raw.headersJson) }
5603
5348
  );
5349
+ return Object.assign(response, { traceId: raw.traceId });
5604
5350
  }
5605
- };
5606
- }
5607
- });
5608
-
5609
- // src/sse.ts
5610
- async function* parseSSEMessages(stream, signal) {
5611
- const reader = stream.getReader();
5612
- const decoder = new TextDecoder();
5613
- let buffer = "";
5614
- try {
5615
- while (true) {
5616
- if (signal?.aborted) break;
5617
- const { done, value } = await reader.read();
5618
- if (done) break;
5619
- buffer += decoder.decode(value, { stream: true });
5620
- const parts = buffer.split(/\r?\n\r?\n/);
5621
- buffer = parts.pop() ?? "";
5622
- for (const part of parts) {
5623
- const lines = part.split(/\r?\n/);
5624
- const dataLines = [];
5625
- let event;
5626
- let id;
5627
- for (const line of lines) {
5628
- if (!line || line.startsWith(":")) continue;
5629
- const separator = line.indexOf(":");
5630
- const field = separator === -1 ? line : line.slice(0, separator);
5631
- let value2 = separator === -1 ? "" : line.slice(separator + 1);
5632
- if (value2.startsWith(" ")) {
5633
- value2 = value2.slice(1);
5634
- }
5635
- if (field === "data") {
5636
- dataLines.push(value2);
5637
- } else if (field === "event") {
5638
- event = value2;
5639
- } else if (field === "id") {
5640
- id = value2;
5641
- }
5642
- }
5643
- if (dataLines.length > 0 || event || id) {
5644
- yield { data: dataLines.join("\n"), event, id };
5645
- }
5351
+ async requestJson(method, path4) {
5352
+ const response = await this.requestResponse(method, path4);
5353
+ const text = await response.text();
5354
+ const value = text ? JSON.parse(text) : null;
5355
+ return Object.assign(value ?? {}, { traceId: response.traceId });
5646
5356
  }
5647
- }
5648
- } finally {
5649
- reader.releaseLock();
5650
- }
5651
- }
5652
- async function* parseSSEStream(stream, signal) {
5653
- for await (const message of parseSSEMessages(stream, signal)) {
5654
- if (!message.data) continue;
5655
- try {
5656
- yield JSON.parse(message.data);
5657
- } catch {
5658
- }
5659
- }
5660
- }
5661
- var init_sse = __esm({
5662
- "src/sse.ts"() {
5663
- "use strict";
5664
- init_esm_shims();
5357
+ async *stream(method, path4, signal) {
5358
+ if (signal?.aborted) return;
5359
+ const request = await serializeRequest(method, path4, { headers: { Accept: "text/event-stream" } });
5360
+ yield* nativeEventStream((emit) => this.client().stream(request, emit), void 0, signal);
5361
+ }
5362
+ };
5665
5363
  }
5666
5364
  });
5667
5365
 
@@ -5764,11 +5462,10 @@ var init_cloud_client = __esm({
5764
5462
  "use strict";
5765
5463
  init_esm_shims();
5766
5464
  init_defaults();
5767
- init_http();
5465
+ init_native_cloud();
5768
5466
  init_models();
5769
- init_sse();
5770
5467
  CloudClient = class _CloudClient {
5771
- http;
5468
+ transport;
5772
5469
  organizationId;
5773
5470
  projectId;
5774
5471
  namespace;
@@ -5776,20 +5473,22 @@ var init_cloud_client = __esm({
5776
5473
  this.organizationId = options?.organizationId;
5777
5474
  this.projectId = options?.projectId;
5778
5475
  this.namespace = options?.namespace ?? NAMESPACE;
5779
- this.http = new HttpClient({
5476
+ this.transport = new NativeCloudTransport({
5780
5477
  baseUrl: options?.apiUrl ?? API_URL,
5781
5478
  apiKey: options?.apiKey ?? API_KEY,
5782
5479
  organizationId: this.organizationId,
5783
5480
  projectId: this.projectId,
5784
5481
  maxRetries: options?.maxRetries ?? MAX_RETRIES,
5785
- retryBackoffMs: options?.retryBackoffMs ?? RETRY_BACKOFF_MS
5482
+ retryBackoffMs: options?.retryBackoffMs ?? RETRY_BACKOFF_MS,
5483
+ timeoutMs: DEFAULT_HTTP_TIMEOUT_MS,
5484
+ userAgent: `tensorlake-typescript-sdk/${SDK_VERSION}`
5786
5485
  });
5787
5486
  }
5788
5487
  static forCloud(options) {
5789
5488
  return new _CloudClient(options);
5790
5489
  }
5791
5490
  close() {
5792
- this.http.close();
5491
+ this.transport.close();
5793
5492
  }
5794
5493
  async upsertApplication(manifest, codeZip, upgradeRunningRequests = false) {
5795
5494
  const applicationManifest = { ...manifest };
@@ -5817,18 +5516,18 @@ var init_cloud_client = __esm({
5817
5516
  "upgrade_requests_to_latest_code",
5818
5517
  String(upgradeRunningRequests)
5819
5518
  );
5820
- await this.http.requestResponse("POST", this.namespacePath("applications"), {
5519
+ await this.transport.requestResponse("POST", this.namespacePath("applications"), {
5821
5520
  body: form
5822
5521
  });
5823
5522
  }
5824
5523
  async deleteApplication(applicationName) {
5825
- await this.http.requestResponse(
5524
+ await this.transport.requestResponse(
5826
5525
  "DELETE",
5827
5526
  this.namespacePath(`applications/${encodeURIComponent(applicationName)}`)
5828
5527
  );
5829
5528
  }
5830
5529
  async deleteSandboxImage(imageName) {
5831
- await this.http.requestResponse(
5530
+ await this.transport.requestResponse(
5832
5531
  "DELETE",
5833
5532
  this.namespacePath(`sandbox-images/${encodeURIComponent(imageName)}`)
5834
5533
  );
@@ -5847,10 +5546,10 @@ var init_cloud_client = __esm({
5847
5546
  options?.organizationId,
5848
5547
  options?.projectId
5849
5548
  );
5850
- const response = await this.http.requestResponse(
5549
+ const response = await this.transport.requestResponse(
5851
5550
  "GET",
5852
5551
  `${base}/by-name/${encodeURIComponent(imageName)}`,
5853
- { allowedErrorStatusCodes: /* @__PURE__ */ new Set([404]) }
5552
+ { statusOnlyCodes: /* @__PURE__ */ new Set([404]) }
5854
5553
  );
5855
5554
  if (response.status === 404) {
5856
5555
  return null;
@@ -5872,7 +5571,7 @@ var init_cloud_client = __esm({
5872
5571
  let path4 = `${base}?pageSize=100`;
5873
5572
  const templates = [];
5874
5573
  while (path4 !== null) {
5875
- const page = await this.http.requestJson(
5574
+ const page = await this.transport.requestJson(
5876
5575
  "GET",
5877
5576
  path4
5878
5577
  );
@@ -5885,7 +5584,7 @@ var init_cloud_client = __esm({
5885
5584
  return templates;
5886
5585
  }
5887
5586
  async applications() {
5888
- const raw = await this.http.requestJson(
5587
+ const raw = await this.transport.requestJson(
5889
5588
  "GET",
5890
5589
  this.namespacePath("applications")
5891
5590
  );
@@ -5894,7 +5593,7 @@ var init_cloud_client = __esm({
5894
5593
  );
5895
5594
  }
5896
5595
  async applicationManifest(applicationName) {
5897
- const raw = await this.http.requestJson(
5596
+ const raw = await this.transport.requestJson(
5898
5597
  "GET",
5899
5598
  this.namespacePath(`applications/${encodeURIComponent(applicationName)}`)
5900
5599
  );
@@ -5904,10 +5603,10 @@ var init_cloud_client = __esm({
5904
5603
  const path4 = this.namespacePath(
5905
5604
  `applications/${encodeURIComponent(applicationName)}`
5906
5605
  );
5907
- const response = inputs.length === 0 ? await this.http.requestResponse("POST", path4, {
5606
+ const response = inputs.length === 0 ? await this.transport.requestResponse("POST", path4, {
5908
5607
  body: new Uint8Array(),
5909
5608
  headers: { Accept: "application/json" }
5910
- }) : inputs.length === 1 && inputs[0].name === "0" ? await this.http.requestResponse("POST", path4, {
5609
+ }) : inputs.length === 1 && inputs[0].name === "0" ? await this.transport.requestResponse("POST", path4, {
5911
5610
  body: toRequestBody(inputs[0].data),
5912
5611
  headers: {
5913
5612
  Accept: "application/json",
@@ -5922,13 +5621,13 @@ var init_cloud_client = __esm({
5922
5621
  return requestId;
5923
5622
  }
5924
5623
  async waitOnRequestCompletion(applicationName, requestId) {
5925
- const stream = await this.http.requestStream(
5624
+ const stream = this.transport.stream(
5926
5625
  "GET",
5927
5626
  this.namespacePath(
5928
5627
  `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/progress`
5929
5628
  )
5930
5629
  );
5931
- for await (const event of parseSSEStream(stream)) {
5630
+ for await (const event of stream) {
5932
5631
  if (Object.prototype.hasOwnProperty.call(event, "RequestFinished")) {
5933
5632
  return;
5934
5633
  }
@@ -5936,7 +5635,7 @@ var init_cloud_client = __esm({
5936
5635
  throw new Error("progress stream ended before request completion");
5937
5636
  }
5938
5637
  async requestMetadata(applicationName, requestId) {
5939
- const raw = await this.http.requestJson(
5638
+ const raw = await this.transport.requestJson(
5940
5639
  "GET",
5941
5640
  this.namespacePath(
5942
5641
  `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}`
@@ -5945,7 +5644,7 @@ var init_cloud_client = __esm({
5945
5644
  return fromSnakeKeys(raw);
5946
5645
  }
5947
5646
  async requestOutput(applicationName, requestId) {
5948
- const response = await this.http.requestResponse(
5647
+ const response = await this.transport.requestResponse(
5949
5648
  "GET",
5950
5649
  this.namespacePath(
5951
5650
  `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/output`
@@ -5963,7 +5662,7 @@ var init_cloud_client = __esm({
5963
5662
  options?.organizationId,
5964
5663
  options?.projectId
5965
5664
  );
5966
- const raw = await this.http.requestJson("GET", base);
5665
+ const raw = await this.transport.requestJson("GET", base);
5967
5666
  const pageSize = Math.max(0, options?.pageSize ?? 100);
5968
5667
  return Object.assign(
5969
5668
  {
@@ -5978,7 +5677,7 @@ var init_cloud_client = __esm({
5978
5677
  options?.organizationId,
5979
5678
  options?.projectId
5980
5679
  );
5981
- const raw = await this.http.requestJson(
5680
+ const raw = await this.transport.requestJson(
5982
5681
  "GET",
5983
5682
  `${base}/${encodeURIComponent(secretId)}`
5984
5683
  );
@@ -6003,24 +5702,24 @@ var init_cloud_client = __esm({
6003
5702
  options?.organizationId,
6004
5703
  options?.projectId
6005
5704
  );
6006
- await this.http.requestResponse(
5705
+ await this.transport.requestResponse(
6007
5706
  "DELETE",
6008
5707
  `${base}/${encodeURIComponent(secretId)}`
6009
5708
  );
6010
5709
  }
6011
5710
  async upsertSecret(base, secret) {
6012
- let response = await this.http.requestResponse("POST", base, {
5711
+ let response = await this.transport.requestResponse("POST", base, {
6013
5712
  json: secret,
6014
5713
  headers: { "Idempotency-Key": nanoid() },
6015
- allowedErrorStatusCodes: /* @__PURE__ */ new Set([409])
5714
+ statusOnlyCodes: /* @__PURE__ */ new Set([409])
6016
5715
  });
6017
5716
  if (response.status === 409) {
6018
5717
  const prefix = base.slice(0, -"/secrets".length);
6019
- const existing = await this.http.requestJson(
5718
+ const existing = await this.transport.requestJson(
6020
5719
  "GET",
6021
5720
  `${prefix}/secret-names/${encodeURIComponent(secret.name)}`
6022
5721
  );
6023
- response = await this.http.requestResponse(
5722
+ response = await this.transport.requestResponse(
6024
5723
  "POST",
6025
5724
  `${base}/${encodeURIComponent(existing.id)}/versions`,
6026
5725
  {
@@ -6046,7 +5745,7 @@ var init_cloud_client = __esm({
6046
5745
  new Blob([toBlobPart(request.buildContext)]),
6047
5746
  "context.tar.gz"
6048
5747
  );
6049
- const response = await this.http.requestResponse(
5748
+ const response = await this.transport.requestResponse(
6050
5749
  "PUT",
6051
5750
  `${trimTrailingSlashes2(buildServicePath)}/builds`,
6052
5751
  { body: form }
@@ -6056,7 +5755,7 @@ var init_cloud_client = __esm({
6056
5755
  }
6057
5756
  async createApplicationBuild(buildServicePath, request, imageContexts) {
6058
5757
  const form = createApplicationBuildForm(request, imageContexts);
6059
- const response = await this.http.requestResponse(
5758
+ const response = await this.transport.requestResponse(
6060
5759
  "POST",
6061
5760
  trimTrailingSlashes2(buildServicePath),
6062
5761
  { body: form }
@@ -6065,39 +5764,39 @@ var init_cloud_client = __esm({
6065
5764
  return fromSnakeKeys(raw);
6066
5765
  }
6067
5766
  async applicationBuildInfo(buildServicePath, applicationBuildId) {
6068
- const raw = await this.http.requestJson(
5767
+ const raw = await this.transport.requestJson(
6069
5768
  "GET",
6070
5769
  `${trimTrailingSlashes2(buildServicePath)}/${encodeURIComponent(applicationBuildId)}`
6071
5770
  );
6072
5771
  return fromSnakeKeys(raw);
6073
5772
  }
6074
5773
  async cancelApplicationBuild(buildServicePath, applicationBuildId) {
6075
- const raw = await this.http.requestJson(
5774
+ const raw = await this.transport.requestJson(
6076
5775
  "POST",
6077
5776
  `${trimTrailingSlashes2(buildServicePath)}/${encodeURIComponent(applicationBuildId)}/cancel`
6078
5777
  );
6079
5778
  return fromSnakeKeys(raw);
6080
5779
  }
6081
5780
  async buildInfo(buildServicePath, buildId) {
6082
- const raw = await this.http.requestJson(
5781
+ const raw = await this.transport.requestJson(
6083
5782
  "GET",
6084
5783
  `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}`
6085
5784
  );
6086
5785
  return fromSnakeKeys(raw);
6087
5786
  }
6088
5787
  async cancelBuild(buildServicePath, buildId) {
6089
- await this.http.requestResponse(
5788
+ await this.transport.requestResponse(
6090
5789
  "POST",
6091
5790
  `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}/cancel`
6092
5791
  );
6093
5792
  }
6094
5793
  async *streamBuildLogs(buildServicePath, buildId, signal) {
6095
- const stream = await this.http.requestStream(
5794
+ const stream = this.transport.stream(
6096
5795
  "GET",
6097
5796
  `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}/logs`,
6098
- { signal }
5797
+ signal
6099
5798
  );
6100
- for await (const event of parseSSEStream(stream, signal)) {
5799
+ for await (const event of stream) {
6101
5800
  yield fromSnakeKeys(event);
6102
5801
  }
6103
5802
  }
@@ -6110,7 +5809,7 @@ var init_cloud_client = __esm({
6110
5809
  input.name
6111
5810
  );
6112
5811
  }
6113
- return this.http.requestResponse("POST", path4, {
5812
+ return this.transport.requestResponse("POST", path4, {
6114
5813
  body: form,
6115
5814
  headers: { Accept: "application/json" }
6116
5815
  });
@@ -6119,10 +5818,10 @@ var init_cloud_client = __esm({
6119
5818
  return `/v1/namespaces/${encodeURIComponent(this.namespace)}/${subpath.replace(/^\/+/, "")}`;
6120
5819
  }
6121
5820
  async existingApplicationPublicEndpointId(applicationName) {
6122
- const response = await this.http.requestResponse(
5821
+ const response = await this.transport.requestResponse(
6123
5822
  "GET",
6124
5823
  this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),
6125
- { allowedErrorStatusCodes: /* @__PURE__ */ new Set([404]) }
5824
+ { statusOnlyCodes: /* @__PURE__ */ new Set([404]) }
6126
5825
  );
6127
5826
  if (response.status === 404) {
6128
5827
  return void 0;