@tensorlakeai/tensorlake 0.0.0-bootstrap.0 → 0.5.145

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 (69) hide show
  1. package/README.md +166 -2
  2. package/bin/function-executor.js +8 -0
  3. package/bin/tensorlake-create-sandbox-image.js +9 -0
  4. package/bin/tensorlake-deploy.cjs +8 -0
  5. package/bin/tensorlake-import-sandbox-image.js +9 -0
  6. package/bin/tensorlake-typescript-function-runner.js +8 -0
  7. package/dist/applications/index.cjs +4821 -0
  8. package/dist/applications/index.cjs.map +1 -0
  9. package/dist/applications/index.d.cts +130 -0
  10. package/dist/applications/index.d.ts +130 -0
  11. package/dist/applications/index.js +4782 -0
  12. package/dist/applications/index.js.map +1 -0
  13. package/dist/function-agent/main.cjs +1838 -0
  14. package/dist/function-agent/main.cjs.map +1 -0
  15. package/dist/function-agent/main.d.cts +3 -0
  16. package/dist/function-agent/main.d.ts +3 -0
  17. package/dist/function-agent/main.js +1825 -0
  18. package/dist/function-agent/main.js.map +1 -0
  19. package/dist/function-executor/main.cjs +4944 -0
  20. package/dist/function-executor/main.cjs.map +1 -0
  21. package/dist/function-executor/main.d.cts +4 -0
  22. package/dist/function-executor/main.d.ts +4 -0
  23. package/dist/function-executor/main.js +4902 -0
  24. package/dist/function-executor/main.js.map +1 -0
  25. package/dist/index.cjs +10184 -0
  26. package/dist/index.cjs.map +1 -0
  27. package/dist/index.d.cts +2431 -0
  28. package/dist/index.d.ts +2431 -0
  29. package/dist/index.js +10108 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/native-worker.cjs +278 -0
  32. package/dist/native-worker.cjs.map +1 -0
  33. package/dist/native-worker.d.cts +2 -0
  34. package/dist/native-worker.d.ts +2 -0
  35. package/dist/native-worker.js +276 -0
  36. package/dist/native-worker.js.map +1 -0
  37. package/dist/remote-CNJ9TmcQ.d.cts +283 -0
  38. package/dist/remote-dblFxKug.d.ts +283 -0
  39. package/dist/sandbox-image-ChzWDeZy.d.cts +357 -0
  40. package/dist/sandbox-image-ChzWDeZy.d.ts +357 -0
  41. package/dist/sandbox-image.cjs +1992 -0
  42. package/dist/sandbox-image.cjs.map +1 -0
  43. package/dist/sandbox-image.d.cts +1 -0
  44. package/dist/sandbox-image.d.ts +1 -0
  45. package/dist/sandbox-image.js +1987 -0
  46. package/dist/sandbox-image.js.map +1 -0
  47. package/lib/libc.cjs +61 -0
  48. package/lib/libc.d.cts +1 -0
  49. package/lib/runtime.cjs +155 -0
  50. package/package.json +104 -4
  51. package/runtime/function-executor/manifest.json +59 -0
  52. package/runtime/function-executor/package/bin/function-executor.js +8 -0
  53. package/runtime/function-executor/package/dist/function-executor/main.js +4902 -0
  54. package/runtime/function-executor/package/dist/function-executor/main.js.map +1 -0
  55. package/runtime/function-executor/package/dist/native-worker.cjs +278 -0
  56. package/runtime/function-executor/package/dist/native-worker.cjs.map +1 -0
  57. package/runtime/function-executor/package/npm-shrinkwrap.json +475 -0
  58. package/runtime/function-executor/package/package.json +22 -0
  59. package/runtime/function-executor/package/proto/README.md +18 -0
  60. package/runtime/function-executor/package/proto/tensorlake/function_executor/proto/function_executor.proto +613 -0
  61. package/runtime/function-executor/package/proto/tensorlake/function_executor/proto/status.proto +42 -0
  62. package/runtime/typescript-function-runner/manifest.json +44 -0
  63. package/runtime/typescript-function-runner/package/bin/tensorlake-typescript-function-runner.js +8 -0
  64. package/runtime/typescript-function-runner/package/dist/function-agent/main.js +1825 -0
  65. package/runtime/typescript-function-runner/package/dist/function-agent/main.js.map +1 -0
  66. package/runtime/typescript-function-runner/package/dist/native-worker.cjs +278 -0
  67. package/runtime/typescript-function-runner/package/dist/native-worker.cjs.map +1 -0
  68. package/runtime/typescript-function-runner/package/npm-shrinkwrap.json +586 -0
  69. package/runtime/typescript-function-runner/package/package.json +25 -0
@@ -0,0 +1,1838 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
+
36
+ // node_modules/tsup/assets/cjs_shims.js
37
+ var getImportMetaUrl, importMetaUrl;
38
+ var init_cjs_shims = __esm({
39
+ "node_modules/tsup/assets/cjs_shims.js"() {
40
+ "use strict";
41
+ getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
42
+ importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
43
+ }
44
+ });
45
+
46
+ // lib/libc.cjs
47
+ var require_libc = __commonJS({
48
+ "lib/libc.cjs"(exports2, module2) {
49
+ "use strict";
50
+ init_cjs_shims();
51
+ function detectLinuxLibc2(fs2, executable = process.execPath) {
52
+ const override = process.env.TENSORLAKE_NODE_LIBC;
53
+ if (override != null) {
54
+ if (override === "gnu" || override === "musl") return override;
55
+ throw new Error("TENSORLAKE_NODE_LIBC must be 'gnu' or 'musl'.");
56
+ }
57
+ let fd;
58
+ try {
59
+ let read2 = function(size, offset) {
60
+ if (!Number.isSafeInteger(offset) || offset < 0) {
61
+ throw new Error("Invalid ELF offset");
62
+ }
63
+ const buffer = Buffer.alloc(size);
64
+ let count2 = 0;
65
+ while (count2 < size) {
66
+ const bytes = fs2.readSync(fd, buffer, count2, size - count2, offset + count2);
67
+ if (bytes === 0) throw new Error("Truncated ELF executable");
68
+ count2 += bytes;
69
+ }
70
+ return buffer;
71
+ };
72
+ var read = read2;
73
+ fd = fs2.openSync(executable, "r");
74
+ const header = read2(64, 0);
75
+ if (header.readUInt32BE(0) !== 2135247942 || header[4] !== 2 || header[5] !== 1) {
76
+ throw new Error("Expected a little-endian ELF64 executable");
77
+ }
78
+ const entrySize = header.readUInt16LE(54);
79
+ const count = header.readUInt16LE(56);
80
+ if (entrySize !== 56 || count === 0 || count > 128) {
81
+ throw new Error("Unsupported ELF program headers");
82
+ }
83
+ const entries = read2(entrySize * count, Number(header.readBigUInt64LE(32)));
84
+ for (let i = 0; i < count; i++) {
85
+ const offset = i * entrySize;
86
+ if (entries.readUInt32LE(offset) !== 3) continue;
87
+ const size = Number(entries.readBigUInt64LE(offset + 32));
88
+ if (size < 2 || size > 4096) throw new Error("Invalid ELF interpreter size");
89
+ const interpreter = read2(size, Number(entries.readBigUInt64LE(offset + 8)));
90
+ if (interpreter[size - 1] !== 0) throw new Error("Unterminated ELF interpreter");
91
+ const name = interpreter.subarray(0, -1).toString("utf8").split("/").at(-1);
92
+ if (name.startsWith("ld-musl-")) return "musl";
93
+ if (name.startsWith("ld-linux-")) return "gnu";
94
+ throw new Error("Unrecognized ELF interpreter");
95
+ }
96
+ throw new Error("No ELF interpreter (statically linked executable)");
97
+ } catch (cause) {
98
+ throw new Error(
99
+ "Unable to detect Linux libc from the Node executable. Set TENSORLAKE_NODE_LIBC to 'gnu' or 'musl' for a nonstandard runtime.",
100
+ { cause }
101
+ );
102
+ } finally {
103
+ if (fd != null) fs2.closeSync(fd);
104
+ }
105
+ }
106
+ module2.exports = { detectLinuxLibc: detectLinuxLibc2 };
107
+ }
108
+ });
109
+
110
+ // src/function-agent/main.ts
111
+ var main_exports = {};
112
+ __export(main_exports, {
113
+ main: () => main
114
+ });
115
+ module.exports = __toCommonJS(main_exports);
116
+ init_cjs_shims();
117
+
118
+ // src/native-binding.ts
119
+ init_cjs_shims();
120
+ var import_libc = __toESM(require_libc(), 1);
121
+ var fs = __toESM(require("fs"), 1);
122
+ var import_node_module = require("module");
123
+ var import_node_path = __toESM(require("path"), 1);
124
+ var import_node_url = require("url");
125
+ var NATIVE_PACKAGES = {
126
+ "darwin-arm64": "@tensorlakeai/native-darwin-arm64",
127
+ "linux-arm64": "@tensorlakeai/native-linux-arm64-gnu",
128
+ "linux-arm64-musl": "@tensorlakeai/native-linux-arm64-musl",
129
+ "linux-x64": "@tensorlakeai/native-linux-x64-gnu",
130
+ "linux-x64-musl": "@tensorlakeai/native-linux-x64-musl",
131
+ "win32-x64": "@tensorlakeai/native-win32-x64"
132
+ };
133
+ function packageRoot() {
134
+ const parent = (0, import_node_url.fileURLToPath)(new URL("../", importMetaUrl));
135
+ if (fs.existsSync(import_node_path.default.join(parent, "package.json"))) return parent;
136
+ const grandparent = (0, import_node_url.fileURLToPath)(new URL("../../", importMetaUrl));
137
+ if (fs.existsSync(import_node_path.default.join(grandparent, "package.json"))) return grandparent;
138
+ return parent;
139
+ }
140
+ var cachedLinuxLibc;
141
+ function linuxLibcFamily(options) {
142
+ if (options.libc != null) return options.libc;
143
+ if (options.report != null) {
144
+ return options.report.header?.glibcVersionRuntime ? "gnu" : "musl";
145
+ }
146
+ if (cachedLinuxLibc != null) return cachedLinuxLibc;
147
+ cachedLinuxLibc = (0, import_libc.detectLinuxLibc)(fs);
148
+ return cachedLinuxLibc;
149
+ }
150
+ function nativeTargetId(platform = process.platform, arch = process.arch, options = {}) {
151
+ const target = `${platform}-${arch}`;
152
+ if (platform !== "linux") return target;
153
+ if (options.libc == null && options.report == null && platform !== process.platform) {
154
+ return target;
155
+ }
156
+ return linuxLibcFamily(options) === "musl" ? `${target}-musl` : target;
157
+ }
158
+ function nativeBindingPath(options = {}) {
159
+ const platform = options.platform ?? process.platform;
160
+ const arch = options.arch ?? process.arch;
161
+ return import_node_path.default.join(
162
+ options.packageRoot ?? packageRoot(),
163
+ "dist",
164
+ "native",
165
+ nativeTargetId(platform, arch, options),
166
+ "tensorlake-node.node"
167
+ );
168
+ }
169
+ function nativePackageName(platform = process.platform, arch = process.arch, options = {}) {
170
+ return NATIVE_PACKAGES[nativeTargetId(platform, arch, options)];
171
+ }
172
+ function loadNative() {
173
+ const target = nativeTargetId();
174
+ const bindingPath = nativeBindingPath();
175
+ const require2 = (0, import_node_module.createRequire)(importMetaUrl);
176
+ if (fs.existsSync(bindingPath)) return require2(bindingPath);
177
+ const packageName = nativePackageName();
178
+ if (!packageName) {
179
+ throw new Error(
180
+ `Tensorlake does not provide a native binding for ${target}.`
181
+ );
182
+ }
183
+ let packageEntry;
184
+ try {
185
+ packageEntry = require2.resolve(packageName);
186
+ } catch (cause) {
187
+ throw new Error(
188
+ `Missing native binding package ${packageName} for ${target}. Reinstall @tensorlakeai/tensorlake without omitting optional dependencies, and install dependencies on the machine where they will run.`,
189
+ { cause }
190
+ );
191
+ }
192
+ return require2(packageEntry);
193
+ }
194
+
195
+ // src/native-worker-client.ts
196
+ init_cjs_shims();
197
+ var import_node_module2 = require("module");
198
+ var import_node_worker_threads = require("worker_threads");
199
+
200
+ // src/native-worker-protocol.ts
201
+ init_cjs_shims();
202
+ var cancelNativeCall = /* @__PURE__ */ Symbol.for("tensorlake.native.cancel.v1");
203
+ var closeNativeHandle = /* @__PURE__ */ Symbol.for("tensorlake.native.close.v1");
204
+
205
+ // src/url.ts
206
+ init_cjs_shims();
207
+
208
+ // src/defaults.ts
209
+ init_cjs_shims();
210
+ var API_URL = process.env.TENSORLAKE_API_URL ?? "https://api.tensorlake.ai";
211
+ var API_KEY = process.env.TENSORLAKE_API_KEY ?? void 0;
212
+ var NAMESPACE = process.env.INDEXIFY_NAMESPACE ?? "default";
213
+ var SANDBOX_PROXY_URL = process.env.TENSORLAKE_SANDBOX_PROXY_URL ?? "https://sandbox.tensorlake.ai";
214
+
215
+ // src/url.ts
216
+ function trimTrailingSlashes(url) {
217
+ return url.endsWith("/") ? url.slice(0, -1) : url;
218
+ }
219
+ function resolveProxyTarget(proxyUrl, sandboxId) {
220
+ try {
221
+ const parsed = new URL(proxyUrl);
222
+ const host = parsed.hostname;
223
+ if (host === "localhost" || host === "127.0.0.1") {
224
+ return {
225
+ baseUrl: trimTrailingSlashes(proxyUrl),
226
+ hostHeader: `${sandboxId}.local`,
227
+ sandboxIdHeader: void 0
228
+ };
229
+ }
230
+ const port = parsed.port ? `:${parsed.port}` : "";
231
+ return {
232
+ baseUrl: `${parsed.protocol}//${host}${port}`,
233
+ hostHeader: void 0,
234
+ sandboxIdHeader: sandboxId
235
+ };
236
+ } catch {
237
+ return {
238
+ baseUrl: `${trimTrailingSlashes(proxyUrl)}/${sandboxId}`,
239
+ hostHeader: void 0,
240
+ sandboxIdHeader: void 0
241
+ };
242
+ }
243
+ }
244
+
245
+ // src/native-worker-client.ts
246
+ var NativeWorkerClient = class {
247
+ constructor(workerPath = () => (0, import_node_module2.createRequire)(importMetaUrl).resolve(
248
+ "@tensorlakeai/tensorlake/internal/native-worker"
249
+ )) {
250
+ this.workerPath = workerPath;
251
+ }
252
+ worker;
253
+ nextId = 1;
254
+ registered = /* @__PURE__ */ new Set();
255
+ pending = /* @__PURE__ */ new Map();
256
+ finalizers = new FinalizationRegistry(
257
+ (id) => this.release(id)
258
+ );
259
+ handle(kind, args, parent) {
260
+ const handle = { id: this.nextId++, kind, args, parent };
261
+ this.finalizers.register(handle, handle.id);
262
+ let closed = false;
263
+ return new Proxy(
264
+ {},
265
+ {
266
+ get: (_target, method) => {
267
+ if (method === "then") return void 0;
268
+ if (method === closeNativeHandle)
269
+ return () => {
270
+ closed = true;
271
+ this.release(handle.id);
272
+ };
273
+ if (method === "connectProxy")
274
+ return (...proxyArgs) => {
275
+ if (closed) throw new Error("Tensorlake native client is closed");
276
+ return this.handle("NativeSandboxProxyClient", proxyArgs, handle);
277
+ };
278
+ if (method === "baseUrl")
279
+ return () => resolveProxyTarget(String(args[0]), String(args[1])).baseUrl;
280
+ if (typeof method !== "string") return void 0;
281
+ return (...callArgs) => {
282
+ if (closed)
283
+ return Promise.reject(
284
+ new Error("Tensorlake native client is closed")
285
+ );
286
+ const emit = typeof callArgs.at(-1) === "function" ? callArgs.pop() : void 0;
287
+ return this.call(handle, method, callArgs, emit);
288
+ };
289
+ }
290
+ }
291
+ );
292
+ }
293
+ call(handle, method, args, emit) {
294
+ const id = this.nextId++;
295
+ let worker;
296
+ const promise = new Promise((resolve, reject) => {
297
+ try {
298
+ worker = this.getWorker();
299
+ this.pending.set(id, { resolve, reject, emit, handle });
300
+ worker.ref();
301
+ if (handle) this.register(handle, worker);
302
+ this.send(worker, {
303
+ type: "call",
304
+ id,
305
+ handleId: handle?.id,
306
+ method,
307
+ args,
308
+ stream: !!emit
309
+ });
310
+ } catch (error) {
311
+ this.pending.delete(id);
312
+ this.unrefIfIdle();
313
+ reject(error);
314
+ }
315
+ });
316
+ promise[cancelNativeCall] = () => {
317
+ const pending = this.pending.get(id);
318
+ if (pending && worker) {
319
+ pending.emit = void 0;
320
+ this.send(worker, { type: "cancel", id });
321
+ }
322
+ };
323
+ return promise;
324
+ }
325
+ getWorker() {
326
+ if (this.worker) return this.worker;
327
+ const worker = new import_node_worker_threads.Worker(this.workerPath(), {
328
+ // The bundled worker needs no application loaders or telemetry preloads.
329
+ // NODE_OPTIONS is parsed independently of execArgv by Node.
330
+ execArgv: [],
331
+ env: { ...process.env, NODE_OPTIONS: "" },
332
+ name: "tensorlake-native"
333
+ });
334
+ this.worker = worker;
335
+ worker.on("message", (message) => {
336
+ const pending = this.pending.get(message.id);
337
+ if (!pending || this.worker !== worker) return;
338
+ if (message.type === "event") {
339
+ Promise.resolve().then(() => pending.emit?.(message.value)).then(
340
+ () => {
341
+ if (this.worker === worker)
342
+ this.send(worker, { type: "ack", id: message.id });
343
+ },
344
+ (error) => {
345
+ this.send(worker, { type: "cancel", id: message.id });
346
+ pending.reject(error);
347
+ }
348
+ );
349
+ return;
350
+ }
351
+ this.pending.delete(message.id);
352
+ if (message.type === "error") {
353
+ const error = new Error(message.error.message);
354
+ error.name = message.error.name;
355
+ error.stack = message.error.stack ?? error.stack;
356
+ pending.reject(error);
357
+ } else {
358
+ pending.resolve(message.value);
359
+ }
360
+ this.unrefIfIdle();
361
+ });
362
+ const fail = (error) => {
363
+ if (this.worker !== worker) return;
364
+ this.worker = void 0;
365
+ this.registered.clear();
366
+ for (const pending of this.pending.values()) pending.reject(error);
367
+ this.pending.clear();
368
+ void worker.terminate();
369
+ };
370
+ worker.on("error", fail);
371
+ worker.on("messageerror", fail);
372
+ worker.on(
373
+ "exit",
374
+ (code) => fail(
375
+ new Error(
376
+ `Tensorlake native worker exited (${code}); in-flight operations were not retried`
377
+ )
378
+ )
379
+ );
380
+ worker.unref();
381
+ return worker;
382
+ }
383
+ register(handle, worker) {
384
+ if (this.registered.has(handle.id)) return;
385
+ if (handle.parent) this.register(handle.parent, worker);
386
+ this.send(worker, {
387
+ type: "create",
388
+ handle: { id: handle.id, kind: handle.kind, args: handle.args },
389
+ parentId: handle.parent?.id
390
+ });
391
+ this.registered.add(handle.id);
392
+ }
393
+ release(handleId) {
394
+ if (this.worker && this.registered.delete(handleId))
395
+ this.send(this.worker, { type: "release", handleId });
396
+ }
397
+ send(worker, message) {
398
+ worker.postMessage(message);
399
+ }
400
+ unrefIfIdle() {
401
+ if (this.pending.size === 0) this.worker?.unref();
402
+ }
403
+ };
404
+ var runtimeKey = /* @__PURE__ */ Symbol.for(
405
+ `tensorlake.native.worker.${false ? "source" : "0.5.145"}.v1`
406
+ );
407
+ var runtimes = globalThis;
408
+ function configureNativeWorker(workerPath) {
409
+ runtimes[runtimeKey] ??= new NativeWorkerClient(workerPath);
410
+ }
411
+
412
+ // src/function-agent/runner.ts
413
+ init_cjs_shims();
414
+ var import_node_crypto3 = require("crypto");
415
+ var import_promises = require("fs/promises");
416
+ var import_node_os = __toESM(require("os"), 1);
417
+ var import_node_path2 = __toESM(require("path"), 1);
418
+ var import_node_url2 = require("url");
419
+ var import_node_vm = require("vm");
420
+ var import_fflate = require("fflate");
421
+
422
+ // src/applications/context.ts
423
+ init_cjs_shims();
424
+ var import_node_async_hooks = require("async_hooks");
425
+
426
+ // src/applications/errors.ts
427
+ init_cjs_shims();
428
+ var SDK_USAGE_ERROR_BRAND = /* @__PURE__ */ Symbol.for("tensorlake.applications.sdk-usage-error.v1");
429
+ var REQUEST_ERROR_BRAND = /* @__PURE__ */ Symbol.for("tensorlake.applications.request-error.v1");
430
+ var FUNCTION_ERROR_BRAND = /* @__PURE__ */ Symbol.for("tensorlake.applications.function-error.v1");
431
+ var TIMEOUT_ERROR_BRAND = /* @__PURE__ */ Symbol.for("tensorlake.applications.timeout-error.v1");
432
+ var TensorlakeApplicationError = class extends Error {
433
+ constructor(message, options) {
434
+ super(message, options);
435
+ this.name = "TensorlakeApplicationError";
436
+ }
437
+ };
438
+ var SDKUsageError = class _SDKUsageError extends TensorlakeApplicationError {
439
+ [SDK_USAGE_ERROR_BRAND] = true;
440
+ static [Symbol.hasInstance](value) {
441
+ if (this !== _SDKUsageError) {
442
+ return Function.prototype[Symbol.hasInstance].call(this, value);
443
+ }
444
+ return isSDKUsageError(value);
445
+ }
446
+ constructor(message) {
447
+ super(message);
448
+ this.name = "SDKUsageError";
449
+ }
450
+ };
451
+ function isSDKUsageError(value) {
452
+ if (typeof value !== "object" || value == null) return false;
453
+ const candidate = value;
454
+ return candidate[SDK_USAGE_ERROR_BRAND] === true && typeof candidate.message === "string";
455
+ }
456
+ var SerializationError = class extends TensorlakeApplicationError {
457
+ constructor(message, options) {
458
+ super(message, options);
459
+ this.name = "SerializationError";
460
+ }
461
+ };
462
+ var DeserializationError = class extends TensorlakeApplicationError {
463
+ constructor(message, options) {
464
+ super(message, options);
465
+ this.name = "DeserializationError";
466
+ }
467
+ };
468
+ var FunctionError = class _FunctionError extends TensorlakeApplicationError {
469
+ [FUNCTION_ERROR_BRAND] = true;
470
+ static [Symbol.hasInstance](value) {
471
+ if (this !== _FunctionError) {
472
+ return Function.prototype[Symbol.hasInstance].call(this, value);
473
+ }
474
+ return isFunctionError(value);
475
+ }
476
+ constructor(message, options) {
477
+ super(message, options);
478
+ this.name = "FunctionError";
479
+ }
480
+ };
481
+ var TimeoutError = class _TimeoutError extends TensorlakeApplicationError {
482
+ [TIMEOUT_ERROR_BRAND] = true;
483
+ static [Symbol.hasInstance](value) {
484
+ if (this !== _TimeoutError) {
485
+ return Function.prototype[Symbol.hasInstance].call(this, value);
486
+ }
487
+ return isTimeoutError(value);
488
+ }
489
+ constructor() {
490
+ super("Timed out.");
491
+ this.name = "TimeoutError";
492
+ }
493
+ };
494
+ function isTimeoutError(value) {
495
+ if (typeof value !== "object" || value == null) return false;
496
+ const candidate = value;
497
+ return candidate[TIMEOUT_ERROR_BRAND] === true && typeof candidate.message === "string";
498
+ }
499
+ function isFunctionError(value) {
500
+ if (typeof value !== "object" || value == null) return false;
501
+ const candidate = value;
502
+ return candidate[FUNCTION_ERROR_BRAND] === true && typeof candidate.message === "string";
503
+ }
504
+ var RequestError = class _RequestError extends TensorlakeApplicationError {
505
+ [REQUEST_ERROR_BRAND] = true;
506
+ static [Symbol.hasInstance](value) {
507
+ if (this !== _RequestError) {
508
+ return Function.prototype[Symbol.hasInstance].call(this, value);
509
+ }
510
+ return isRequestError(value);
511
+ }
512
+ constructor(message, options) {
513
+ super(message, options);
514
+ this.name = "RequestError";
515
+ }
516
+ };
517
+ function isRequestError(value) {
518
+ if (typeof value !== "object" || value == null) return false;
519
+ const candidate = value;
520
+ return candidate[REQUEST_ERROR_BRAND] === true && typeof candidate.message === "string";
521
+ }
522
+
523
+ // src/applications/headers.ts
524
+ init_cjs_shims();
525
+ var HEADERS_BRAND = /* @__PURE__ */ Symbol.for("tensorlake.applications.headers.v1");
526
+ var Headers = class _Headers {
527
+ [HEADERS_BRAND] = true;
528
+ #items;
529
+ #lookup;
530
+ static [Symbol.hasInstance](value) {
531
+ if (this !== _Headers) {
532
+ return Function.prototype[Symbol.hasInstance].call(this, value);
533
+ }
534
+ return isHeaders(value);
535
+ }
536
+ constructor(headers = []) {
537
+ const entries = headers instanceof _Headers ? [...headers] : Symbol.iterator in Object(headers) ? [...headers] : Object.entries(headers);
538
+ const lookup = /* @__PURE__ */ new Map();
539
+ this.#items = Object.freeze(entries.map(([name, value]) => {
540
+ if (typeof name !== "string" || typeof value !== "string") {
541
+ throw new TypeError("Headers require string names and values");
542
+ }
543
+ const item = Object.freeze([name, value]);
544
+ const key = name.toLowerCase();
545
+ lookup.set(key, [...lookup.get(key) ?? [], value]);
546
+ return item;
547
+ }));
548
+ this.#lookup = lookup;
549
+ Object.freeze(this);
550
+ }
551
+ get(name) {
552
+ return this.#lookup.get(name.toLowerCase())?.at(-1);
553
+ }
554
+ getAll(name) {
555
+ return Object.freeze([...this.#lookup.get(name.toLowerCase()) ?? []]);
556
+ }
557
+ has(name) {
558
+ return this.#lookup.has(name.toLowerCase());
559
+ }
560
+ entries() {
561
+ return this.#items[Symbol.iterator]();
562
+ }
563
+ [Symbol.iterator]() {
564
+ return this.entries();
565
+ }
566
+ };
567
+ function isHeaders(value) {
568
+ if (typeof value !== "object" || value == null) return false;
569
+ const candidate = value;
570
+ return candidate[HEADERS_BRAND] === true && typeof candidate.get === "function" && typeof candidate.getAll === "function" && typeof candidate.has === "function" && typeof candidate[Symbol.iterator] === "function";
571
+ }
572
+
573
+ // src/applications/serialization.ts
574
+ init_cjs_shims();
575
+ var import_node_crypto = require("crypto");
576
+
577
+ // src/applications/file.ts
578
+ init_cjs_shims();
579
+ var FILE_BRAND = /* @__PURE__ */ Symbol.for("tensorlake.applications.file.v1");
580
+ var File = class _File {
581
+ [FILE_BRAND] = true;
582
+ content;
583
+ contentType;
584
+ static [Symbol.hasInstance](value) {
585
+ if (this !== _File) {
586
+ return Function.prototype[Symbol.hasInstance].call(this, value);
587
+ }
588
+ return isFile(value);
589
+ }
590
+ constructor(content, contentType) {
591
+ if (!contentType.trim()) {
592
+ throw new SDKUsageError("File contentType cannot be empty");
593
+ }
594
+ this.content = content instanceof Uint8Array ? content : new Uint8Array(content);
595
+ this.contentType = contentType;
596
+ }
597
+ };
598
+ function isFile(value) {
599
+ if (typeof value !== "object" || value == null) return false;
600
+ const candidate = value;
601
+ return candidate[FILE_BRAND] === true && candidate.content instanceof Uint8Array && typeof candidate.contentType === "string" && candidate.contentType.trim().length > 0;
602
+ }
603
+
604
+ // src/applications/http-body.ts
605
+ init_cjs_shims();
606
+ var HTTP_BODY_BRAND = /* @__PURE__ */ Symbol.for("tensorlake.applications.http-body.v1");
607
+ var HttpBody = class _HttpBody {
608
+ [HTTP_BODY_BRAND] = true;
609
+ content;
610
+ contentType;
611
+ static [Symbol.hasInstance](value) {
612
+ if (this !== _HttpBody) {
613
+ return Function.prototype[Symbol.hasInstance].call(this, value);
614
+ }
615
+ return isHttpBody(value);
616
+ }
617
+ constructor(content, contentType) {
618
+ this.content = content instanceof Uint8Array ? content : new Uint8Array(content);
619
+ this.contentType = contentType;
620
+ }
621
+ text(encoding = "utf-8") {
622
+ return new TextDecoder(encoding, { fatal: true }).decode(this.content);
623
+ }
624
+ json() {
625
+ return JSON.parse(this.text());
626
+ }
627
+ };
628
+ function isHttpBody(value) {
629
+ if (typeof value !== "object" || value == null) return false;
630
+ const candidate = value;
631
+ return candidate[HTTP_BODY_BRAND] === true && candidate.content instanceof Uint8Array && (candidate.contentType === void 0 || typeof candidate.contentType === "string");
632
+ }
633
+
634
+ // src/applications/serialization.ts
635
+ var textEncoder = new TextEncoder();
636
+ var textDecoder = new TextDecoder("utf-8", { fatal: true });
637
+ function assertJSONValue(value, path3, seen) {
638
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
639
+ if (typeof value === "number") {
640
+ if (!Number.isFinite(value)) throw new SerializationError(`${path3} contains a non-finite number`);
641
+ return;
642
+ }
643
+ if (typeof value !== "object") {
644
+ throw new SerializationError(`${path3} contains unsupported ${typeof value}`);
645
+ }
646
+ if (isFile(value)) {
647
+ throw new SerializationError(`${path3} contains a nested File; File is only supported as a direct value`);
648
+ }
649
+ if (isHttpBody(value)) {
650
+ throw new SerializationError(
651
+ `${path3} contains a nested HttpBody; HttpBody is only supported as a direct value`
652
+ );
653
+ }
654
+ if (seen.has(value)) throw new SerializationError(`${path3} contains a cycle`);
655
+ if (Object.getPrototypeOf(value) !== Object.prototype && !Array.isArray(value)) {
656
+ throw new SerializationError(`${path3} contains unsupported ${value.constructor?.name ?? "object"}`);
657
+ }
658
+ seen.add(value);
659
+ if (Array.isArray(value)) {
660
+ for (let index = 0; index < value.length; index += 1) {
661
+ if (!Object.prototype.hasOwnProperty.call(value, index)) {
662
+ throw new SerializationError(`${path3} contains a sparse array entry at index ${index}`);
663
+ }
664
+ assertJSONValue(value[index], `${path3}[${index}]`, seen);
665
+ }
666
+ } else {
667
+ for (const [key, item] of Object.entries(value)) {
668
+ assertJSONValue(item, `${path3}.${key}`, seen);
669
+ }
670
+ }
671
+ seen.delete(value);
672
+ }
673
+ function serializeValue(value) {
674
+ if (isFile(value)) {
675
+ return { data: value.content, contentType: value.contentType, encoding: "raw" };
676
+ }
677
+ if (isHttpBody(value)) {
678
+ return {
679
+ data: value.content,
680
+ contentType: value.contentType ?? "",
681
+ encoding: "raw"
682
+ };
683
+ }
684
+ try {
685
+ assertJSONValue(value, "value", /* @__PURE__ */ new Set());
686
+ return {
687
+ data: textEncoder.encode(JSON.stringify(value)),
688
+ contentType: "application/json; charset=UTF-8",
689
+ encoding: "json"
690
+ };
691
+ } catch (error) {
692
+ if (error instanceof SerializationError) throw error;
693
+ throw new SerializationError("Failed to serialize JSON value", { cause: error });
694
+ }
695
+ }
696
+ function deserializeJSON(data) {
697
+ try {
698
+ return JSON.parse(textDecoder.decode(data));
699
+ } catch (error) {
700
+ throw new DeserializationError("Failed to deserialize JSON value", { cause: error });
701
+ }
702
+ }
703
+
704
+ // src/applications/context.ts
705
+ function validateRequestStateKey(key) {
706
+ if (typeof key !== "string") {
707
+ throw new SDKUsageError(`State key must be a string, got: ${String(key)}`);
708
+ }
709
+ }
710
+ function serializeRequestStateValue(value) {
711
+ const serialized = serializeValue(value);
712
+ if (serialized.encoding !== "json") {
713
+ throw new SDKUsageError("Request state values must be JSON values");
714
+ }
715
+ return serialized.data;
716
+ }
717
+ function validateCounterMetric(name, value) {
718
+ if (typeof name !== "string") {
719
+ throw new SDKUsageError(`Counter name must be a string, got: ${String(name)}`);
720
+ }
721
+ if (typeof value !== "number" || !Number.isInteger(value)) {
722
+ throw new SDKUsageError(`Counter value must be an int, got: ${String(value)}`);
723
+ }
724
+ if (!Number.isSafeInteger(value)) {
725
+ throw new SDKUsageError(`Counter value must be a safe int, got: ${String(value)}`);
726
+ }
727
+ }
728
+ function validateTimerMetric(name, value) {
729
+ if (typeof name !== "string") {
730
+ throw new SDKUsageError(`Timer name must be a string, got: ${String(name)}`);
731
+ }
732
+ if (typeof value !== "number" || !Number.isFinite(value)) {
733
+ throw new SDKUsageError(`Timer value must be a finite number, got: ${String(value)}`);
734
+ }
735
+ }
736
+ function isPlainRecord(value) {
737
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
738
+ const prototype = Object.getPrototypeOf(value);
739
+ return prototype === Object.prototype || prototype === null;
740
+ }
741
+ function validateProgressUpdate(current, total, options) {
742
+ if (!Number.isFinite(current) || !Number.isFinite(total) || total < 0 || current < 0) {
743
+ throw new SDKUsageError("Progress current and total must be non-negative finite numbers");
744
+ }
745
+ if (options != null && !isPlainRecord(options)) {
746
+ throw new SDKUsageError("Progress options must be an object");
747
+ }
748
+ if (options?.message != null && typeof options.message !== "string") {
749
+ throw new SDKUsageError("Progress message must be a string");
750
+ }
751
+ if (options?.attributes != null) {
752
+ if (!isPlainRecord(options.attributes)) {
753
+ throw new SDKUsageError("Progress attributes must be an object of string key/value pairs");
754
+ }
755
+ for (const key of Reflect.ownKeys(options.attributes)) {
756
+ if (typeof key !== "string") {
757
+ throw new SDKUsageError("Progress attributes must contain only string keys and values");
758
+ }
759
+ const value = options.attributes[key];
760
+ if (typeof value !== "string") {
761
+ throw new SDKUsageError("Progress attributes must contain only string keys and values");
762
+ }
763
+ }
764
+ }
765
+ }
766
+ var REQUEST_CONTEXT_STORAGE_KEY = /* @__PURE__ */ Symbol.for(
767
+ "tensorlake.applications.request-context-storage.v1"
768
+ );
769
+ function requestContextStorage() {
770
+ const target = globalThis;
771
+ target[REQUEST_CONTEXT_STORAGE_KEY] ??= new import_node_async_hooks.AsyncLocalStorage();
772
+ return target[REQUEST_CONTEXT_STORAGE_KEY];
773
+ }
774
+ function runWithRequestContext(context, callback) {
775
+ return requestContextStorage().run(context, callback);
776
+ }
777
+
778
+ // src/applications/function.ts
779
+ init_cjs_shims();
780
+ var import_node_async_hooks2 = require("async_hooks");
781
+ var import_node_crypto2 = require("crypto");
782
+
783
+ // src/applications/schema.ts
784
+ init_cjs_shims();
785
+ var import_ajv = __toESM(require("ajv"), 1);
786
+ var import__ = __toESM(require("ajv/dist/2020.js"), 1);
787
+ var ajvDraft7 = new import_ajv.default({ allErrors: true, strict: false });
788
+ var ajv2020 = new import__.default({ allErrors: true, strict: false });
789
+ var validatorCache = /* @__PURE__ */ new WeakMap();
790
+ function compileValidator(jsonSchema) {
791
+ const dialect = jsonSchema.$schema;
792
+ const engine = typeof dialect === "string" && /\/draft-07\/schema#?$/.test(dialect) ? ajvDraft7 : ajv2020;
793
+ const validate = engine.compile(jsonSchema);
794
+ return {
795
+ validate,
796
+ errorsText: (errors) => engine.errorsText(errors, { separator: "; " })
797
+ };
798
+ }
799
+ function validateWithSchema(valueSchema, value, label) {
800
+ if (valueSchema._file) {
801
+ if (!isFile(value)) {
802
+ throw new SDKUsageError(`${label} must be a Tensorlake File`);
803
+ }
804
+ return value;
805
+ }
806
+ if (valueSchema._httpBody) {
807
+ if (!isHttpBody(value)) {
808
+ throw new SDKUsageError(`${label} must be a Tensorlake HttpBody`);
809
+ }
810
+ return value;
811
+ }
812
+ if (isFile(value)) {
813
+ throw new SDKUsageError(`${label} must use schema.file() for a Tensorlake File`);
814
+ }
815
+ if (isHttpBody(value)) {
816
+ throw new SDKUsageError(
817
+ `${label} must use schema.httpBody() for a Tensorlake HttpBody`
818
+ );
819
+ }
820
+ let cached = validatorCache.get(valueSchema);
821
+ if (cached == null) {
822
+ try {
823
+ cached = compileValidator(valueSchema.jsonSchema);
824
+ } catch (error) {
825
+ const details = error instanceof Error ? error.message : String(error);
826
+ throw new SDKUsageError(`${label} uses an invalid JSON schema: ${details}`);
827
+ }
828
+ validatorCache.set(valueSchema, cached);
829
+ }
830
+ if (!cached.validate(value)) {
831
+ const details = cached.errorsText(cached.validate.errors);
832
+ throw new SDKUsageError(`${label} does not match its schema: ${details}`);
833
+ }
834
+ return value;
835
+ }
836
+
837
+ // src/applications/registry.ts
838
+ init_cjs_shims();
839
+
840
+ // src/applications/function.ts
841
+ var TAIL_CALL_BRAND = /* @__PURE__ */ Symbol.for(
842
+ "tensorlake.applications.tail-call.v1"
843
+ );
844
+ var FUNCTION_RUNTIME_STORAGE_KEY = /* @__PURE__ */ Symbol.for(
845
+ "tensorlake.applications.function-runtime-storage.v1"
846
+ );
847
+ var PROMISE_INSTRUMENTED_KEY = /* @__PURE__ */ Symbol.for(
848
+ "tensorlake.applications.promise-instrumented.v3"
849
+ );
850
+ var PROMISE_THEN_INSTRUMENTED_KEY = /* @__PURE__ */ Symbol.for(
851
+ "tensorlake.applications.promise-then-instrumented.v1"
852
+ );
853
+ var DURABLE_THENABLE_REGISTRY_KEY = /* @__PURE__ */ Symbol.for(
854
+ "tensorlake.applications.durable-thenable-registry.v2"
855
+ );
856
+ var INTERNAL_PROMISE_AGGREGATE_DEPTH_KEY = /* @__PURE__ */ Symbol.for(
857
+ "tensorlake.applications.internal-promise-aggregate-depth.v1"
858
+ );
859
+ function runtimeStorage() {
860
+ const target = globalThis;
861
+ target[FUNCTION_RUNTIME_STORAGE_KEY] ??= new import_node_async_hooks2.AsyncLocalStorage();
862
+ return target[FUNCTION_RUNTIME_STORAGE_KEY];
863
+ }
864
+ function currentFunctionRuntime() {
865
+ return runtimeStorage().getStore();
866
+ }
867
+ function runWithFunctionRuntime(runtime, callback) {
868
+ return runtimeStorage().run(runtime, callback);
869
+ }
870
+ function isDurableThenable(value) {
871
+ if (typeof value !== "object" && typeof value !== "function" || value == null) {
872
+ return false;
873
+ }
874
+ return durableThenableRegistry().has(value);
875
+ }
876
+ function isDetachedDurableThenable(value) {
877
+ const provenance = provenanceForDurableThenable(value);
878
+ return provenance?.detached === true || provenance?.assimilation != null && !provenance.assimilation.active;
879
+ }
880
+ function durableThenableRegistry() {
881
+ const target = globalThis;
882
+ target[DURABLE_THENABLE_REGISTRY_KEY] ??= /* @__PURE__ */ new WeakMap();
883
+ return target[DURABLE_THENABLE_REGISTRY_KEY];
884
+ }
885
+ function newDurableThenableMetadata() {
886
+ return {
887
+ aggregateExpectations: [],
888
+ provenanceExpectations: []
889
+ };
890
+ }
891
+ function provenanceForDurableThenable(value) {
892
+ if (typeof value !== "object" && typeof value !== "function" || value == null) {
893
+ return void 0;
894
+ }
895
+ return durableThenableRegistry().get(value);
896
+ }
897
+ function registerDetachedDurableThenable(value) {
898
+ const registry = durableThenableRegistry();
899
+ registry.set(value, {
900
+ metadata: registry.get(value)?.metadata ?? newDurableThenableMetadata(),
901
+ detached: true
902
+ });
903
+ return value;
904
+ }
905
+ function inheritDurableThenable(value, source) {
906
+ const provenance = durableThenableRegistry().get(source);
907
+ if (provenance == null) return value;
908
+ durableThenableRegistry().set(value, provenance);
909
+ if (provenance.assimilation == null) {
910
+ provenance.metadata.provenanceExpectations.push({
911
+ value,
912
+ creatorAsyncId: (0, import_node_async_hooks2.executionAsyncId)()
913
+ });
914
+ }
915
+ return value;
916
+ }
917
+ function associateAssimilationWithAggregate(registration, scope) {
918
+ if (!registration.active || scope.settled) return;
919
+ finishDurableAssimilation(registration);
920
+ registration.detach();
921
+ }
922
+ function finishDurableAssimilation(registration) {
923
+ if (!registration.active) return;
924
+ registration.active = false;
925
+ }
926
+ function trackDurableAggregate(runtime, result, durableContenders, markResult) {
927
+ const scope = {
928
+ settled: false,
929
+ metadata: /* @__PURE__ */ new Set()
930
+ };
931
+ if (markResult) {
932
+ registerDetachedDurableThenable(result);
933
+ }
934
+ const creatorAsyncId = (0, import_node_async_hooks2.executionAsyncId)();
935
+ for (const contender of durableContenders) {
936
+ const provenance = provenanceForDurableThenable(contender);
937
+ if (provenance == null) continue;
938
+ if (provenance.assimilation != null) {
939
+ associateAssimilationWithAggregate(provenance.assimilation, scope);
940
+ } else {
941
+ provenance.metadata.aggregateExpectations.push({
942
+ scope,
943
+ creatorAsyncId
944
+ });
945
+ }
946
+ if (scope.metadata.has(provenance.metadata)) continue;
947
+ const { metadata } = provenance;
948
+ scope.metadata.add(metadata);
949
+ }
950
+ const settle = () => {
951
+ if (scope.settled) return;
952
+ scope.settled = true;
953
+ for (const metadata of scope.metadata) {
954
+ for (let index = metadata.aggregateExpectations.length - 1; index >= 0; index -= 1) {
955
+ if (metadata.aggregateExpectations[index].scope === scope) {
956
+ metadata.aggregateExpectations.splice(index, 1);
957
+ }
958
+ }
959
+ }
960
+ scope.metadata.clear();
961
+ };
962
+ if (runtime.trackPromiseSettlement?.(result, settle) !== true) settle();
963
+ }
964
+ function promiseAggregateObservation(kind) {
965
+ let settleLifetime;
966
+ const ordinaryLifetime = new Promise((resolve) => {
967
+ settleLifetime = resolve;
968
+ });
969
+ let contenderCount;
970
+ let fulfillmentCount = 0;
971
+ let rejectionCount = 0;
972
+ let settled = false;
973
+ const maybeSettle = () => {
974
+ if (settled) return;
975
+ const canNoLongerAdvance = kind === "any" ? contenderCount != null && rejectionCount === contenderCount : kind === "all" ? rejectionCount > 0 || contenderCount != null && fulfillmentCount === contenderCount : contenderCount != null && fulfillmentCount + rejectionCount === contenderCount;
976
+ if (!canNoLongerAdvance) return;
977
+ settled = true;
978
+ settleLifetime();
979
+ };
980
+ return {
981
+ ordinaryLifetime,
982
+ allOrdinaryValuesObservable: true,
983
+ observeFulfillment: () => {
984
+ fulfillmentCount += 1;
985
+ maybeSettle();
986
+ },
987
+ observeRejection: () => {
988
+ rejectionCount += 1;
989
+ maybeSettle();
990
+ },
991
+ finishIteration: (count) => {
992
+ contenderCount = count;
993
+ maybeSettle();
994
+ }
995
+ };
996
+ }
997
+ function observePromiseAggregateContender(normalized, observation) {
998
+ if (typeof normalized !== "object" && typeof normalized !== "function" || normalized == null) {
999
+ observation.allOrdinaryValuesObservable = false;
1000
+ return normalized;
1001
+ }
1002
+ let observedSettled = false;
1003
+ const observed = /* @__PURE__ */ Object.create(null);
1004
+ Object.defineProperty(observed, "then", {
1005
+ configurable: true,
1006
+ get: () => {
1007
+ const then = Reflect.get(normalized, "then", normalized);
1008
+ if (typeof then !== "function") return then;
1009
+ return function observedThen(onfulfilled, onrejected) {
1010
+ return Reflect.apply(then, normalized, [
1011
+ function observedFulfillment(value) {
1012
+ if (!observedSettled) {
1013
+ observedSettled = true;
1014
+ observation.observeFulfillment();
1015
+ }
1016
+ return typeof onfulfilled === "function" ? Reflect.apply(onfulfilled, this, [value]) : void 0;
1017
+ },
1018
+ function observedRejection(reason) {
1019
+ if (!observedSettled) {
1020
+ observedSettled = true;
1021
+ observation.observeRejection();
1022
+ }
1023
+ if (typeof onrejected === "function") {
1024
+ return Reflect.apply(onrejected, this, [reason]);
1025
+ }
1026
+ throw reason;
1027
+ }
1028
+ ]);
1029
+ };
1030
+ }
1031
+ });
1032
+ return observed;
1033
+ }
1034
+ function observedPromiseConstructor(constructor, observeNormalized) {
1035
+ const facade = function PromiseAggregateObservedConstructor(executor) {
1036
+ return Reflect.construct(
1037
+ constructor,
1038
+ [executor],
1039
+ constructor
1040
+ );
1041
+ };
1042
+ Object.defineProperty(facade, "resolve", {
1043
+ configurable: true,
1044
+ get: () => {
1045
+ const promiseResolve = Reflect.get(constructor, "resolve", constructor);
1046
+ if (typeof promiseResolve !== "function") return promiseResolve;
1047
+ return (value) => {
1048
+ const normalized = Reflect.apply(promiseResolve, constructor, [value]);
1049
+ return observeNormalized(normalized);
1050
+ };
1051
+ }
1052
+ });
1053
+ return facade;
1054
+ }
1055
+ function isInternalPromiseAggregate() {
1056
+ const target = globalThis;
1057
+ return (target[INTERNAL_PROMISE_AGGREGATE_DEPTH_KEY] ?? 0) > 0;
1058
+ }
1059
+ function installPromiseInstrumentation() {
1060
+ const target = globalThis;
1061
+ if (target[PROMISE_THEN_INSTRUMENTED_KEY] !== true) {
1062
+ const originalThen = Promise.prototype.then;
1063
+ Object.defineProperty(Promise.prototype, "then", {
1064
+ ...Object.getOwnPropertyDescriptor(Promise.prototype, "then"),
1065
+ value: function then(onfulfilled, onrejected) {
1066
+ const result = Reflect.apply(
1067
+ originalThen,
1068
+ this,
1069
+ [onfulfilled, onrejected]
1070
+ );
1071
+ if (isDetachedDurableThenable(this)) {
1072
+ currentFunctionRuntime()?.trackDurablePromiseConsumption?.(result);
1073
+ }
1074
+ return result;
1075
+ }
1076
+ });
1077
+ target[PROMISE_THEN_INSTRUMENTED_KEY] = true;
1078
+ }
1079
+ if (target[PROMISE_INSTRUMENTED_KEY] === true) return;
1080
+ const originalRace = Promise.race;
1081
+ const originalAny = Promise.any;
1082
+ const originalAll = Promise.all;
1083
+ const originalAllSettled = Promise.allSettled;
1084
+ const originalResolve = Promise.resolve;
1085
+ Object.defineProperty(Promise, "resolve", {
1086
+ ...Object.getOwnPropertyDescriptor(Promise, "resolve"),
1087
+ value: function resolve(value) {
1088
+ const result = Reflect.apply(originalResolve, this, [value]);
1089
+ if (isDurableThenable(value)) inheritDurableThenable(result, value);
1090
+ return result;
1091
+ }
1092
+ });
1093
+ Object.defineProperty(Promise, "race", {
1094
+ ...Object.getOwnPropertyDescriptor(Promise, "race"),
1095
+ value: function race(values) {
1096
+ const runtime = currentFunctionRuntime();
1097
+ if (runtime?.trackMixedPromiseRace == null) {
1098
+ return Reflect.apply(originalRace, this, [values]);
1099
+ }
1100
+ const durableContenders = [];
1101
+ let ordinaryContenderCount = 0;
1102
+ const trackedValues = {
1103
+ *[Symbol.iterator]() {
1104
+ for (const value of values) {
1105
+ yield value;
1106
+ }
1107
+ }
1108
+ };
1109
+ const observedConstructor = observedPromiseConstructor(
1110
+ this,
1111
+ (normalized) => {
1112
+ if (isDurableThenable(normalized)) {
1113
+ durableContenders.push(normalized);
1114
+ } else {
1115
+ ordinaryContenderCount += 1;
1116
+ }
1117
+ return normalized;
1118
+ }
1119
+ );
1120
+ const construct = () => Reflect.apply(
1121
+ originalRace,
1122
+ observedConstructor,
1123
+ [trackedValues]
1124
+ );
1125
+ const result = runtime.runPromiseAggregateConstruction?.(construct) ?? construct();
1126
+ if (durableContenders.length > 0) {
1127
+ trackDurableAggregate(
1128
+ runtime,
1129
+ result,
1130
+ durableContenders,
1131
+ !isInternalPromiseAggregate()
1132
+ );
1133
+ }
1134
+ if (durableContenders.length > 0 && ordinaryContenderCount > 0) {
1135
+ runtime.trackMixedPromiseRace(result);
1136
+ }
1137
+ return result;
1138
+ }
1139
+ });
1140
+ Object.defineProperty(Promise, "any", {
1141
+ ...Object.getOwnPropertyDescriptor(Promise, "any"),
1142
+ value: function any(values) {
1143
+ const runtime = currentFunctionRuntime();
1144
+ if (runtime?.trackMixedPromiseRace == null) {
1145
+ return Reflect.apply(originalAny, this, [values]);
1146
+ }
1147
+ const durableContenders = [];
1148
+ let ordinaryContenderCount = 0;
1149
+ const observation = promiseAggregateObservation("any");
1150
+ const trackedValues = {
1151
+ *[Symbol.iterator]() {
1152
+ for (const value of values) {
1153
+ yield value;
1154
+ }
1155
+ }
1156
+ };
1157
+ const observedConstructor = observedPromiseConstructor(
1158
+ this,
1159
+ (normalized) => {
1160
+ if (isDurableThenable(normalized)) {
1161
+ durableContenders.push(normalized);
1162
+ return normalized;
1163
+ }
1164
+ ordinaryContenderCount += 1;
1165
+ return observePromiseAggregateContender(normalized, observation);
1166
+ }
1167
+ );
1168
+ const construct = () => Reflect.apply(
1169
+ originalAny,
1170
+ observedConstructor,
1171
+ [trackedValues]
1172
+ );
1173
+ const result = runtime.runPromiseAggregateConstruction?.(construct) ?? construct();
1174
+ observation.finishIteration(ordinaryContenderCount);
1175
+ if (durableContenders.length > 0) {
1176
+ trackDurableAggregate(
1177
+ runtime,
1178
+ result,
1179
+ durableContenders,
1180
+ !isInternalPromiseAggregate()
1181
+ );
1182
+ }
1183
+ if (durableContenders.length > 0 && ordinaryContenderCount > 0) {
1184
+ if (observation.allOrdinaryValuesObservable) {
1185
+ runtime.trackMixedPromiseRace(result, [observation.ordinaryLifetime, result]);
1186
+ } else {
1187
+ runtime.trackMixedPromiseRace(result);
1188
+ }
1189
+ }
1190
+ return result;
1191
+ }
1192
+ });
1193
+ Object.defineProperty(Promise, "all", {
1194
+ ...Object.getOwnPropertyDescriptor(Promise, "all"),
1195
+ value: function all(values) {
1196
+ const runtime = currentFunctionRuntime();
1197
+ if (runtime?.trackMixedPromiseRace == null) {
1198
+ return Reflect.apply(originalAll, this, [values]);
1199
+ }
1200
+ const durableContenders = [];
1201
+ let ordinaryContenderCount = 0;
1202
+ const observation = promiseAggregateObservation("all");
1203
+ const trackedValues = {
1204
+ *[Symbol.iterator]() {
1205
+ for (const value of values) {
1206
+ yield value;
1207
+ }
1208
+ }
1209
+ };
1210
+ const observedConstructor = observedPromiseConstructor(
1211
+ this,
1212
+ (normalized) => {
1213
+ if (isDurableThenable(normalized)) {
1214
+ durableContenders.push(normalized);
1215
+ return normalized;
1216
+ }
1217
+ ordinaryContenderCount += 1;
1218
+ return observePromiseAggregateContender(normalized, observation);
1219
+ }
1220
+ );
1221
+ const construct = () => Reflect.apply(
1222
+ originalAll,
1223
+ observedConstructor,
1224
+ [trackedValues]
1225
+ );
1226
+ const result = runtime.runPromiseAggregateConstruction?.(construct) ?? construct();
1227
+ observation.finishIteration(ordinaryContenderCount);
1228
+ if (durableContenders.length > 0) {
1229
+ trackDurableAggregate(
1230
+ runtime,
1231
+ result,
1232
+ durableContenders,
1233
+ !isInternalPromiseAggregate()
1234
+ );
1235
+ }
1236
+ if (durableContenders.length > 0 && ordinaryContenderCount > 0) {
1237
+ if (observation.allOrdinaryValuesObservable) {
1238
+ runtime.trackMixedPromiseRace(result, [observation.ordinaryLifetime, result]);
1239
+ } else {
1240
+ runtime.trackMixedPromiseRace(result);
1241
+ }
1242
+ }
1243
+ return result;
1244
+ }
1245
+ });
1246
+ Object.defineProperty(Promise, "allSettled", {
1247
+ ...Object.getOwnPropertyDescriptor(Promise, "allSettled"),
1248
+ value: function allSettled(values) {
1249
+ const runtime = currentFunctionRuntime();
1250
+ if (runtime?.trackMixedPromiseRace == null) {
1251
+ return Reflect.apply(
1252
+ originalAllSettled,
1253
+ this,
1254
+ [values]
1255
+ );
1256
+ }
1257
+ const durableContenders = [];
1258
+ let ordinaryContenderCount = 0;
1259
+ const observation = promiseAggregateObservation("all_settled");
1260
+ const trackedValues = {
1261
+ *[Symbol.iterator]() {
1262
+ for (const value of values) yield value;
1263
+ }
1264
+ };
1265
+ const observedConstructor = observedPromiseConstructor(
1266
+ this,
1267
+ (normalized) => {
1268
+ if (isDurableThenable(normalized)) {
1269
+ durableContenders.push(normalized);
1270
+ return normalized;
1271
+ }
1272
+ ordinaryContenderCount += 1;
1273
+ return observePromiseAggregateContender(normalized, observation);
1274
+ }
1275
+ );
1276
+ const construct = () => Reflect.apply(
1277
+ originalAllSettled,
1278
+ observedConstructor,
1279
+ [trackedValues]
1280
+ );
1281
+ const result = runtime.runPromiseAggregateConstruction?.(construct) ?? construct();
1282
+ observation.finishIteration(ordinaryContenderCount);
1283
+ if (durableContenders.length > 0) {
1284
+ trackDurableAggregate(
1285
+ runtime,
1286
+ result,
1287
+ durableContenders,
1288
+ !isInternalPromiseAggregate()
1289
+ );
1290
+ }
1291
+ if (durableContenders.length > 0 && ordinaryContenderCount > 0) {
1292
+ if (observation.allOrdinaryValuesObservable) {
1293
+ runtime.trackMixedPromiseRace(result, [observation.ordinaryLifetime, result]);
1294
+ } else {
1295
+ runtime.trackMixedPromiseRace(result);
1296
+ }
1297
+ }
1298
+ return result;
1299
+ }
1300
+ });
1301
+ target[PROMISE_INSTRUMENTED_KEY] = true;
1302
+ }
1303
+ function validateArguments(definition, supplied) {
1304
+ const args = [...supplied];
1305
+ if (args.length > definition.parameters.length) {
1306
+ throw new SDKUsageError(`${definition.name} expected at most ${definition.parameters.length} arguments, received ${args.length}`);
1307
+ }
1308
+ definition.parameters.forEach((parameter, index) => {
1309
+ if (index >= args.length || args[index] === void 0) {
1310
+ if (parameter.hasDefault) args[index] = parameter.defaultValue;
1311
+ else if (parameter.required) throw new SDKUsageError(`${definition.name} is missing argument '${parameter.name}'`);
1312
+ return;
1313
+ }
1314
+ validateWithSchema(parameter.schema, args[index], `${definition.name}.${parameter.name}`);
1315
+ });
1316
+ return args;
1317
+ }
1318
+ async function executeHandlerResult(definition, suppliedArgs) {
1319
+ const args = validateArguments(definition, suppliedArgs);
1320
+ const result = definition.handler(...args);
1321
+ if (result == null || typeof result.then !== "function") {
1322
+ throw new SDKUsageError(`Tensorlake handler '${definition.name}' must be async and return a Promise`);
1323
+ }
1324
+ const output = await result;
1325
+ if (isTailCall(output)) {
1326
+ return output;
1327
+ }
1328
+ validateWithSchema(definition.returns, output, `${definition.name} return value`);
1329
+ return output;
1330
+ }
1331
+ function isTailCall(value) {
1332
+ if (typeof value !== "object" || value == null) return false;
1333
+ const candidate = value;
1334
+ return candidate[TAIL_CALL_BRAND] === true && candidate.kind === "tensorlake-tail-call" && typeof candidate.definition === "object" && candidate.definition != null && Array.isArray(candidate.args);
1335
+ }
1336
+
1337
+ // src/function-agent/runner.ts
1338
+ installPromiseInstrumentation();
1339
+ var RESERVED_ENVIRONMENT_TARGETS = /* @__PURE__ */ new Set([
1340
+ "PYTHONFAULTHANDLER",
1341
+ "LD_PRELOAD",
1342
+ "LD_LIBRARY_PATH",
1343
+ "DYLD_INSERT_LIBRARIES",
1344
+ "PYTHONHOME",
1345
+ "PYTHONPATH",
1346
+ "NODE_OPTIONS",
1347
+ "NODE_PATH"
1348
+ ]);
1349
+ var nativeImport = (0, import_node_vm.compileFunction)(
1350
+ "return import(specifier)",
1351
+ ["specifier"],
1352
+ { importModuleDynamically: import_node_vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER }
1353
+ );
1354
+ function deferred() {
1355
+ let resolve;
1356
+ let reject;
1357
+ const promise = new Promise((resolveValue, rejectValue) => {
1358
+ resolve = resolveValue;
1359
+ reject = rejectValue;
1360
+ });
1361
+ return { promise, resolve, reject };
1362
+ }
1363
+ function durableHash(values) {
1364
+ const hash = (0, import_node_crypto3.createHash)("sha256");
1365
+ for (const value of values) {
1366
+ const bytes = Buffer.from(value, "utf8");
1367
+ const length = Buffer.alloc(8);
1368
+ length.writeBigUInt64BE(BigInt(bytes.byteLength));
1369
+ hash.update(length);
1370
+ hash.update(bytes);
1371
+ hash.update("|");
1372
+ }
1373
+ return hash.digest("hex");
1374
+ }
1375
+ function safeArchivePath(root, archivePath) {
1376
+ const output = import_node_path2.default.resolve(root, archivePath);
1377
+ if (output !== root && !output.startsWith(`${root}${import_node_path2.default.sep}`)) {
1378
+ throw new Error(`Application archive contains unsafe path '${archivePath}'`);
1379
+ }
1380
+ return output;
1381
+ }
1382
+ function decodeBase64(value) {
1383
+ return new Uint8Array(Buffer.from(value, "base64"));
1384
+ }
1385
+ function encodeBase64(value) {
1386
+ return Buffer.from(value).toString("base64");
1387
+ }
1388
+ function deserializeValue(value) {
1389
+ const data = decodeBase64(value.data_base64);
1390
+ if (value.content_type.toLowerCase().includes("json")) return deserializeJSON(data);
1391
+ return new File(data, value.content_type || "application/octet-stream");
1392
+ }
1393
+ function serializeArgument(value) {
1394
+ const serialized = serializeValue(value);
1395
+ return {
1396
+ source: "data",
1397
+ data_base64: encodeBase64(serialized.data),
1398
+ metadata_base64: "",
1399
+ content_type: serialized.contentType
1400
+ };
1401
+ }
1402
+ function applyResolvedEnvironment(assignment) {
1403
+ const rawEnvironment = assignment.resolved_environment ?? [];
1404
+ const targets = /* @__PURE__ */ new Set();
1405
+ for (const item of rawEnvironment) {
1406
+ if (item == null || typeof item.target !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(item.target) || RESERVED_ENVIRONMENT_TARGETS.has(item.target) || item.target.startsWith("TENSORLAKE_") || targets.has(item.target) || typeof item.value !== "string" || item.value.includes("\0")) {
1407
+ throw new Error("Resolved environment entry is invalid");
1408
+ }
1409
+ targets.add(item.target);
1410
+ }
1411
+ for (const item of rawEnvironment) process.env[item.target] = item.value;
1412
+ for (const item of rawEnvironment) item.value = "";
1413
+ assignment.resolved_environment = [];
1414
+ }
1415
+ function failureFromResult(result) {
1416
+ if (result.outcome === "timed_out") return new TimeoutError();
1417
+ if (result.reason === "request_error") return new RequestError("Function call failed");
1418
+ return new FunctionError(`Function call failed: ${result.reason}`);
1419
+ }
1420
+ var FunctionAgentRunner = class {
1421
+ constructor(core) {
1422
+ this.core = core;
1423
+ }
1424
+ attempts = /* @__PURE__ */ new Map();
1425
+ applications = /* @__PURE__ */ new Map();
1426
+ initializationSent = false;
1427
+ async run() {
1428
+ for (; ; ) {
1429
+ const input = JSON.parse(await this.core.nextInput());
1430
+ switch (input.type) {
1431
+ case "assignment":
1432
+ void this.startAssignment(input.assignment);
1433
+ break;
1434
+ case "call_result":
1435
+ this.attempts.get(input.attempt_id)?.deliverCallResult(
1436
+ input.function_call_id,
1437
+ input
1438
+ );
1439
+ break;
1440
+ case "request_state_result":
1441
+ this.attempts.get(input.result.attempt_id)?.deliverStateResult(input.result);
1442
+ break;
1443
+ case "cancel":
1444
+ this.attempts.get(input.attempt_id)?.cancel();
1445
+ break;
1446
+ case "shutdown":
1447
+ return;
1448
+ }
1449
+ }
1450
+ }
1451
+ async startAssignment(assignment) {
1452
+ try {
1453
+ applyResolvedEnvironment(assignment);
1454
+ const application = await this.loadApplication(assignment);
1455
+ if (!this.initializationSent) {
1456
+ await this.submit({ type: "initialized" });
1457
+ this.initializationSent = true;
1458
+ }
1459
+ const definition = application.getFunction(assignment.function);
1460
+ const attempt = new AttemptRuntime(assignment, definition, this.submit.bind(this));
1461
+ this.attempts.set(assignment.attempt_id, attempt);
1462
+ await attempt.run();
1463
+ } catch (error) {
1464
+ if (!this.initializationSent) {
1465
+ await this.submit({ type: "initialized" });
1466
+ this.initializationSent = true;
1467
+ }
1468
+ await this.submit({
1469
+ type: "failure",
1470
+ attempt_id: assignment.attempt_id,
1471
+ reason: "function_error",
1472
+ message: error instanceof Error ? error.stack ?? error.message : String(error)
1473
+ });
1474
+ } finally {
1475
+ this.attempts.delete(assignment.attempt_id);
1476
+ }
1477
+ }
1478
+ loadApplication(assignment) {
1479
+ let application = this.applications.get(assignment.application_code_sha256);
1480
+ if (application == null) {
1481
+ application = unpackApplication(assignment);
1482
+ this.applications.set(assignment.application_code_sha256, application);
1483
+ }
1484
+ return application;
1485
+ }
1486
+ submit(output) {
1487
+ return this.core.submitOutput(JSON.stringify(output));
1488
+ }
1489
+ };
1490
+ var AttemptRuntime = class {
1491
+ constructor(assignment, definition, submit) {
1492
+ this.assignment = assignment;
1493
+ this.definition = definition;
1494
+ this.submit = submit;
1495
+ this.previousDurableId = assignment.function_run_id;
1496
+ }
1497
+ controller = new AbortController();
1498
+ callResults = /* @__PURE__ */ new Map();
1499
+ stateResults = /* @__PURE__ */ new Map();
1500
+ previousDurableId;
1501
+ nextStateSequence = 1;
1502
+ async run() {
1503
+ try {
1504
+ const args = await deserializeAssignmentArguments(this.definition, this.assignment.inputs);
1505
+ const output = await runWithFunctionRuntime(
1506
+ this,
1507
+ () => runWithRequestContext(
1508
+ this.requestContext(),
1509
+ () => executeHandlerResult(this.definition, args)
1510
+ )
1511
+ );
1512
+ if (isTailCall(output)) {
1513
+ const callId = await this.createTailCall(output);
1514
+ await this.submit({
1515
+ type: "success",
1516
+ attempt_id: this.assignment.attempt_id,
1517
+ result: { type: "call_graph", output_function_call_id: callId }
1518
+ });
1519
+ return;
1520
+ }
1521
+ const serialized = serializeValue(output);
1522
+ await this.submit({
1523
+ type: "success",
1524
+ attempt_id: this.assignment.attempt_id,
1525
+ result: {
1526
+ type: "value",
1527
+ output_base64: encodeBase64(serialized.data),
1528
+ metadata_base64: "",
1529
+ content_type: serialized.contentType
1530
+ }
1531
+ });
1532
+ } catch (error) {
1533
+ if (this.controller.signal.aborted) return;
1534
+ await this.submit({
1535
+ type: "failure",
1536
+ attempt_id: this.assignment.attempt_id,
1537
+ reason: isRequestError(error) ? "request_error" : "function_error",
1538
+ message: error instanceof Error ? error.stack ?? error.message : String(error)
1539
+ });
1540
+ }
1541
+ }
1542
+ cancel() {
1543
+ if (!this.controller.signal.aborted) {
1544
+ this.controller.abort(new FunctionError("Function execution was cancelled"));
1545
+ }
1546
+ for (const waiter of this.callResults.values()) waiter.reject(this.controller.signal.reason);
1547
+ for (const waiter of this.stateResults.values()) waiter.reject(this.controller.signal.reason);
1548
+ this.callResults.clear();
1549
+ this.stateResults.clear();
1550
+ }
1551
+ deliverCallResult(functionCallId, result) {
1552
+ const waiter = this.callResults.get(functionCallId);
1553
+ if (waiter == null) return;
1554
+ this.callResults.delete(functionCallId);
1555
+ waiter.resolve(result);
1556
+ }
1557
+ deliverStateResult(result) {
1558
+ const waiter = this.stateResults.get(result.operation_id);
1559
+ if (waiter == null) return;
1560
+ this.stateResults.delete(result.operation_id);
1561
+ waiter.resolve(result);
1562
+ }
1563
+ invoke(definition, args) {
1564
+ return this.runChild(definition, args, 0);
1565
+ }
1566
+ async runFuture(future) {
1567
+ if (future.delaySeconds > 0) {
1568
+ await this.submit({ type: "suspend", attempt_id: this.assignment.attempt_id });
1569
+ await new Promise((resolve, reject) => {
1570
+ const timer = setTimeout(resolve, future.delaySeconds * 1e3);
1571
+ this.controller.signal.addEventListener("abort", () => {
1572
+ clearTimeout(timer);
1573
+ reject(this.controller.signal.reason);
1574
+ }, { once: true });
1575
+ });
1576
+ await this.submit({ type: "resume", attempt_id: this.assignment.attempt_id });
1577
+ }
1578
+ return this.runChild(future.definition, future.args, 0);
1579
+ }
1580
+ async reduce(definition, items, initial, hasInitial) {
1581
+ let values = items;
1582
+ let accumulator = initial;
1583
+ if (!hasInitial) {
1584
+ if (items.length === 0) throw new SDKUsageError("reduce of empty iterable with no initial value");
1585
+ [accumulator, ...values] = items;
1586
+ }
1587
+ if (values.length === 0) return accumulator;
1588
+ const calls = [];
1589
+ let previous;
1590
+ for (const item of values) {
1591
+ const id = this.nextDurableId(definition, "ReduceStep");
1592
+ calls.push({
1593
+ function_call_id: id,
1594
+ function_name: definition.name,
1595
+ inputs: [
1596
+ previous == null ? serializeArgument(accumulator) : { source: "function_run_output", function_call_id: previous },
1597
+ serializeArgument(item)
1598
+ ],
1599
+ call_metadata_base64: this.callMetadata(id, definition.name, "reduce")
1600
+ });
1601
+ previous = id;
1602
+ }
1603
+ await this.submit({ type: "call_batch", attempt_id: this.assignment.attempt_id, calls });
1604
+ return this.watch(previous);
1605
+ }
1606
+ async runChild(definition, args, _delaySeconds) {
1607
+ const id = this.nextDurableId(definition);
1608
+ await this.submit({
1609
+ type: "call_batch",
1610
+ attempt_id: this.assignment.attempt_id,
1611
+ calls: [{
1612
+ function_call_id: id,
1613
+ function_name: definition.name,
1614
+ inputs: args.map(serializeArgument),
1615
+ call_metadata_base64: this.callMetadata(id, definition.name, "call")
1616
+ }]
1617
+ });
1618
+ return this.watch(id);
1619
+ }
1620
+ async watch(functionCallId) {
1621
+ const result = deferred();
1622
+ this.callResults.set(functionCallId, result);
1623
+ await this.submit({
1624
+ type: "watch",
1625
+ attempt_id: this.assignment.attempt_id,
1626
+ function_call_id: functionCallId
1627
+ });
1628
+ const resolved = await result.promise;
1629
+ if (resolved.outcome !== "success") throw failureFromResult(resolved);
1630
+ return deserializeValue({
1631
+ data_base64: resolved.output_base64,
1632
+ metadata_base64: resolved.metadata_base64,
1633
+ content_type: resolved.content_type
1634
+ });
1635
+ }
1636
+ async createTailCall(tailCall) {
1637
+ const id = this.nextDurableId(tailCall.definition);
1638
+ await this.submit({
1639
+ type: "call_batch",
1640
+ attempt_id: this.assignment.attempt_id,
1641
+ calls: [{
1642
+ function_call_id: id,
1643
+ function_name: tailCall.definition.name,
1644
+ inputs: tailCall.args.map(serializeArgument),
1645
+ call_metadata_base64: this.callMetadata(id, tailCall.definition.name, "tail_call")
1646
+ }]
1647
+ });
1648
+ return id;
1649
+ }
1650
+ nextDurableId(definition, operation = "FunctionCall") {
1651
+ const id = durableHash([
1652
+ this.assignment.function_run_id,
1653
+ this.previousDurableId,
1654
+ operation,
1655
+ definition.name
1656
+ ]);
1657
+ this.previousDurableId = id;
1658
+ return id;
1659
+ }
1660
+ callMetadata(id, functionName, operation) {
1661
+ return Buffer.from(JSON.stringify({
1662
+ format: "tensorlake.typescript.function-call.v1",
1663
+ id,
1664
+ functionName,
1665
+ operation
1666
+ })).toString("base64");
1667
+ }
1668
+ requestContext() {
1669
+ return {
1670
+ requestId: this.assignment.request_id,
1671
+ headers: new Headers(
1672
+ (this.assignment.request_headers ?? []).map(({ name, value }) => [name, value])
1673
+ ),
1674
+ signal: this.controller.signal,
1675
+ state: {
1676
+ get: async (key, defaultValue) => {
1677
+ validateRequestStateKey(key);
1678
+ const result = await this.requestState({ operation: "get", key });
1679
+ if (result.result !== "get" || result.value_base64 == null) return defaultValue;
1680
+ return deserializeJSON(decodeBase64(result.value_base64));
1681
+ },
1682
+ set: async (key, value) => {
1683
+ validateRequestStateKey(key);
1684
+ const encoded = encodeBase64(serializeRequestStateValue(value));
1685
+ await this.requestState({ operation: "set", key, value_base64: encoded });
1686
+ }
1687
+ },
1688
+ metrics: {
1689
+ counter: async (name, value = 1) => validateCounterMetric(name, value),
1690
+ timer: async (name, value) => validateTimerMetric(name, value)
1691
+ },
1692
+ progress: {
1693
+ update: async (current, total, options) => {
1694
+ validateProgressUpdate(current, total, options);
1695
+ await this.submit({
1696
+ type: "progress",
1697
+ attempt_id: this.assignment.attempt_id,
1698
+ message: JSON.stringify({ current, total, ...options })
1699
+ });
1700
+ }
1701
+ }
1702
+ };
1703
+ }
1704
+ async requestState(operation) {
1705
+ const operationId = `${this.assignment.attempt_id}:state:${this.nextStateSequence}`;
1706
+ this.nextStateSequence += 1;
1707
+ const result = deferred();
1708
+ this.stateResults.set(operationId, result);
1709
+ await this.submit({
1710
+ type: "request_state",
1711
+ attempt_id: this.assignment.attempt_id,
1712
+ operation_id: operationId,
1713
+ operation
1714
+ });
1715
+ return result.promise;
1716
+ }
1717
+ };
1718
+ async function unpackApplication(assignment) {
1719
+ const archive = decodeBase64(assignment.application_code_base64);
1720
+ const actualHash = (0, import_node_crypto3.createHash)("sha256").update(archive).digest("hex");
1721
+ if (actualHash !== assignment.application_code_sha256) {
1722
+ throw new Error(
1723
+ `Application code hash mismatch: expected ${assignment.application_code_sha256}, got ${actualHash}`
1724
+ );
1725
+ }
1726
+ const root = await (0, import_promises.mkdtemp)(import_node_path2.default.join(import_node_os.default.tmpdir(), "tensorlake-typescript-app-"));
1727
+ const files = (0, import_fflate.unzipSync)(archive);
1728
+ for (const [name, content] of Object.entries(files)) {
1729
+ const destination = safeArchivePath(root, name);
1730
+ if (name.endsWith("/")) {
1731
+ await (0, import_promises.mkdir)(destination, { recursive: true });
1732
+ continue;
1733
+ }
1734
+ await (0, import_promises.mkdir)(import_node_path2.default.dirname(destination), { recursive: true });
1735
+ await (0, import_promises.writeFile)(destination, content, { mode: 384 });
1736
+ }
1737
+ const manifest = JSON.parse(
1738
+ await (0, import_promises.readFile)(import_node_path2.default.join(root, ".tensorlake_code_manifest.json"), "utf8")
1739
+ );
1740
+ if (manifest.format_version !== 2 || manifest.runtime !== "typescript") {
1741
+ throw new Error("Application code is not a Tensorlake TypeScript bundle");
1742
+ }
1743
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
1744
+ if ((manifest.minimum_node_major ?? 24) > nodeMajor) {
1745
+ throw new Error(`Application requires Node ${manifest.minimum_node_major} or newer; runner has ${nodeMajor}`);
1746
+ }
1747
+ if (manifest.module == null) throw new Error("Application manifest does not name a runtime module");
1748
+ const modulePath = safeArchivePath(root, manifest.module);
1749
+ const runtime = await nativeImport((0, import_node_url2.pathToFileURL)(modulePath).href);
1750
+ if (typeof runtime.__tensorlakeGetFunction !== "function") {
1751
+ throw new Error("Application runtime does not export __tensorlakeGetFunction");
1752
+ }
1753
+ return {
1754
+ root,
1755
+ getFunction(name) {
1756
+ if (manifest.functions?.[name] == null) {
1757
+ throw new Error(`Function '${name}' is not present in the application bundle`);
1758
+ }
1759
+ const definition = runtime.__tensorlakeGetFunction?.(name);
1760
+ if (definition?.name !== name) {
1761
+ throw new Error(`Application runtime resolved '${name}' as '${String(definition?.name)}'`);
1762
+ }
1763
+ return definition;
1764
+ }
1765
+ };
1766
+ }
1767
+ async function deserializeAssignmentArguments(definition, inputs) {
1768
+ if (inputs.length === 0) return [];
1769
+ if (inputs.some((input) => input.source_function_call_id != null) || inputs.length > 1) {
1770
+ return inputs.map(deserializeValue);
1771
+ }
1772
+ let data = decodeBase64(inputs[0].data_base64);
1773
+ let contentType = inputs[0].content_type;
1774
+ if (contentType.toLowerCase().startsWith("message/http")) {
1775
+ const marker = Buffer.from("\r\n\r\n");
1776
+ const bytes = Buffer.from(data);
1777
+ const split = bytes.indexOf(marker);
1778
+ if (split < 0) throw new Error("Invalid message/http application input");
1779
+ const lines = bytes.subarray(0, split).toString("utf8").split("\r\n");
1780
+ lines.shift();
1781
+ for (const line of lines) {
1782
+ const colon = line.indexOf(":");
1783
+ if (colon > 0 && line.slice(0, colon).trim().toLowerCase() === "content-type") {
1784
+ contentType = line.slice(colon + 1).trim();
1785
+ }
1786
+ }
1787
+ data = new Uint8Array(bytes.subarray(split + marker.byteLength));
1788
+ }
1789
+ if (definition.parameters.length === 0) return [];
1790
+ const first = definition.parameters[0];
1791
+ if (definition.parameters.length === 1 && first?.schema._httpBody) {
1792
+ return [new HttpBody(data, contentType)];
1793
+ }
1794
+ if (data.byteLength === 0 && !first?.schema._file) return [];
1795
+ if (first?.schema._file) return [new File(data, contentType || "application/octet-stream")];
1796
+ if (!contentType.toLowerCase().includes("json")) {
1797
+ throw new Error(`Expected application/json input, got ${contentType}`);
1798
+ }
1799
+ return [deserializeJSON(data)];
1800
+ }
1801
+
1802
+ // src/function-agent/main.ts
1803
+ function parseArgs(args) {
1804
+ const values = /* @__PURE__ */ new Map();
1805
+ for (let index = 0; index < args.length; index += 1) {
1806
+ const key = args[index];
1807
+ const value = args[index + 1];
1808
+ if (!key?.startsWith("--") || value == null || value.startsWith("--")) {
1809
+ throw new Error(`Expected --name value argument, got '${key ?? ""}'`);
1810
+ }
1811
+ values.set(key.slice(2), value);
1812
+ index += 1;
1813
+ }
1814
+ const functionServiceUrl = values.get("function-service-url");
1815
+ const registrationToken = values.get("registration-token");
1816
+ if (functionServiceUrl == null || registrationToken == null) {
1817
+ throw new Error("--function-service-url and --registration-token are required");
1818
+ }
1819
+ return {
1820
+ functionServiceUrl,
1821
+ registrationToken,
1822
+ ...values.has("agent-id") ? { agentId: values.get("agent-id") } : {},
1823
+ ...values.has("incarnation") ? { incarnation: values.get("incarnation") } : {},
1824
+ ...values.has("secret-service-workload-url") ? { secretServiceWorkloadUrl: values.get("secret-service-workload-url") } : {},
1825
+ ...values.has("credential-request-timeout-ms") ? { credentialRequestTimeoutMs: Number(values.get("credential-request-timeout-ms")) } : {}
1826
+ };
1827
+ }
1828
+ async function main(args = process.argv.slice(2)) {
1829
+ configureNativeWorker(() => new URL("../native-worker.cjs", importMetaUrl));
1830
+ const binding = loadNative();
1831
+ const core = new binding.FunctionAgentCore(parseArgs(args));
1832
+ return new FunctionAgentRunner(core).run();
1833
+ }
1834
+ // Annotate the CommonJS export names for ESM import in node:
1835
+ 0 && (module.exports = {
1836
+ main
1837
+ });
1838
+ //# sourceMappingURL=main.cjs.map