@tasker-systems/tasker 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,12 +5,8 @@ import { dirname, join } from 'path';
5
5
  import { fileURLToPath } from 'url';
6
6
  import { readdir } from 'fs/promises';
7
7
 
8
- var __create = Object.create;
9
8
  var __defProp = Object.defineProperty;
10
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
12
- var __getProtoOf = Object.getPrototypeOf;
13
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
10
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
15
11
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
16
12
  }) : x)(function(x) {
@@ -18,1689 +14,12 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
18
14
  throw Error('Dynamic require of "' + x + '" is not supported');
19
15
  });
20
16
  var __esm = (fn, res) => function __init() {
21
- return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res;
17
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, { get: all[name], enumerable: true });
22
22
  };
23
- var __commonJS2 = (cb, mod3) => function __require2() {
24
- return mod3 || (0, cb[__getOwnPropNames2(cb)[0]])((mod3 = { exports: {} }).exports, mod3), mod3.exports;
25
- };
26
- var __export = (target, all) => {
27
- for (var name in all)
28
- __defProp(target, name, { get: all[name], enumerable: true });
29
- };
30
- var __copyProps = (to, from, except, desc) => {
31
- if (from && typeof from === "object" || typeof from === "function") {
32
- for (let key of __getOwnPropNames2(from))
33
- if (!__hasOwnProp.call(to, key) && key !== except)
34
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
35
- }
36
- return to;
37
- };
38
- var __toESM = (mod3, isNodeMode, target) => (target = mod3 != null ? __create(__getProtoOf(mod3)) : {}, __copyProps(
39
- // If the importer is in node compatibility mode or this is not an ESM
40
- // file that has been converted to a CommonJS file using a Babel-
41
- // compatible transform (i.e. "__esModule" has not been set), then set
42
- // "default" to the CommonJS "module.exports" for node compatibility.
43
- __defProp(target, "default", { value: mod3, enumerable: true }) ,
44
- mod3
45
- ));
46
-
47
- // src/ffi/runtime-interface.ts
48
- var BaseTaskerRuntime;
49
- var init_runtime_interface = __esm({
50
- "src/ffi/runtime-interface.ts"() {
51
- BaseTaskerRuntime = class {
52
- /**
53
- * Helper to parse JSON string from FFI
54
- */
55
- parseJson(jsonStr) {
56
- if (jsonStr === null || jsonStr === "") {
57
- return null;
58
- }
59
- try {
60
- return JSON.parse(jsonStr);
61
- } catch {
62
- return null;
63
- }
64
- }
65
- /**
66
- * Helper to stringify JSON for FFI
67
- */
68
- toJson(value) {
69
- return JSON.stringify(value);
70
- }
71
- };
72
- }
73
- });
74
-
75
- // src/ffi/deno-runtime.ts
76
- var deno_runtime_exports = {};
77
- __export(deno_runtime_exports, {
78
- DenoRuntime: () => DenoRuntime
79
- });
80
- var DenoRuntime;
81
- var init_deno_runtime = __esm({
82
- "src/ffi/deno-runtime.ts"() {
83
- init_runtime_interface();
84
- DenoRuntime = class extends BaseTaskerRuntime {
85
- name = "deno";
86
- lib = null;
87
- encoder = new TextEncoder();
88
- get isLoaded() {
89
- return this.lib !== null;
90
- }
91
- async load(libraryPath) {
92
- if (this.lib !== null) {
93
- return;
94
- }
95
- if (typeof Deno === "undefined") {
96
- throw new Error("Deno runtime not detected");
97
- }
98
- this.lib = Deno.dlopen(libraryPath, {
99
- get_version: {
100
- parameters: [],
101
- result: "pointer"
102
- },
103
- get_rust_version: {
104
- parameters: [],
105
- result: "pointer"
106
- },
107
- health_check: {
108
- parameters: [],
109
- result: "i32"
110
- },
111
- is_worker_running: {
112
- parameters: [],
113
- result: "i32"
114
- },
115
- bootstrap_worker: {
116
- parameters: ["buffer"],
117
- result: "pointer"
118
- },
119
- get_worker_status: {
120
- parameters: [],
121
- result: "pointer"
122
- },
123
- stop_worker: {
124
- parameters: [],
125
- result: "pointer"
126
- },
127
- transition_to_graceful_shutdown: {
128
- parameters: [],
129
- result: "pointer"
130
- },
131
- poll_step_events: {
132
- parameters: [],
133
- result: "pointer"
134
- },
135
- poll_in_process_events: {
136
- parameters: [],
137
- result: "pointer"
138
- },
139
- complete_step_event: {
140
- parameters: ["buffer", "buffer"],
141
- result: "i32"
142
- },
143
- checkpoint_yield_step_event: {
144
- parameters: ["buffer", "buffer"],
145
- result: "i32"
146
- },
147
- get_ffi_dispatch_metrics: {
148
- parameters: [],
149
- result: "pointer"
150
- },
151
- check_starvation_warnings: {
152
- parameters: [],
153
- result: "void"
154
- },
155
- cleanup_timeouts: {
156
- parameters: [],
157
- result: "void"
158
- },
159
- log_error: {
160
- parameters: ["buffer", "buffer"],
161
- result: "void"
162
- },
163
- log_warn: {
164
- parameters: ["buffer", "buffer"],
165
- result: "void"
166
- },
167
- log_info: {
168
- parameters: ["buffer", "buffer"],
169
- result: "void"
170
- },
171
- log_debug: {
172
- parameters: ["buffer", "buffer"],
173
- result: "void"
174
- },
175
- log_trace: {
176
- parameters: ["buffer", "buffer"],
177
- result: "void"
178
- },
179
- free_rust_string: {
180
- parameters: ["pointer"],
181
- result: "void"
182
- },
183
- // Client API functions (TAS-231)
184
- client_create_task: {
185
- parameters: ["buffer"],
186
- result: "pointer"
187
- },
188
- client_get_task: {
189
- parameters: ["buffer"],
190
- result: "pointer"
191
- },
192
- client_list_tasks: {
193
- parameters: ["buffer"],
194
- result: "pointer"
195
- },
196
- client_cancel_task: {
197
- parameters: ["buffer"],
198
- result: "pointer"
199
- },
200
- client_list_task_steps: {
201
- parameters: ["buffer"],
202
- result: "pointer"
203
- },
204
- client_get_step: {
205
- parameters: ["buffer", "buffer"],
206
- result: "pointer"
207
- },
208
- client_get_step_audit_history: {
209
- parameters: ["buffer", "buffer"],
210
- result: "pointer"
211
- },
212
- client_health_check: {
213
- parameters: [],
214
- result: "pointer"
215
- }
216
- });
217
- }
218
- unload() {
219
- if (this.lib) {
220
- this.lib.close();
221
- this.lib = null;
222
- }
223
- }
224
- ensureLoaded() {
225
- if (!this.lib) {
226
- throw new Error("Native library not loaded. Call load() first.");
227
- }
228
- return this.lib.symbols;
229
- }
230
- /**
231
- * Creates a null-terminated C string buffer.
232
- * With 'buffer' FFI type, we return Uint8Array directly.
233
- */
234
- toCString(str) {
235
- return this.encoder.encode(`${str}\0`);
236
- }
237
- // biome-ignore lint/suspicious/noExplicitAny: Deno PointerValue type
238
- fromCString(ptr) {
239
- if (ptr === null || Deno.UnsafePointer.equals(ptr, null)) {
240
- return null;
241
- }
242
- const view = new Deno.UnsafePointerView(ptr);
243
- return view.getCString();
244
- }
245
- getVersion() {
246
- const symbols = this.ensureLoaded();
247
- const result = symbols.get_version();
248
- const version = this.fromCString(result) ?? "unknown";
249
- if (result !== null) symbols.free_rust_string(result);
250
- return version;
251
- }
252
- getRustVersion() {
253
- const symbols = this.ensureLoaded();
254
- const result = symbols.get_rust_version();
255
- const version = this.fromCString(result) ?? "unknown";
256
- if (result !== null) symbols.free_rust_string(result);
257
- return version;
258
- }
259
- healthCheck() {
260
- const symbols = this.ensureLoaded();
261
- return symbols.health_check() === 1;
262
- }
263
- bootstrapWorker(config) {
264
- const symbols = this.ensureLoaded();
265
- const configBuf = config ? this.toCString(this.toJson(config)) : null;
266
- const result = symbols.bootstrap_worker(configBuf);
267
- const jsonStr = this.fromCString(result);
268
- if (result !== null) symbols.free_rust_string(result);
269
- const parsed = this.parseJson(jsonStr);
270
- return parsed ?? {
271
- success: false,
272
- status: "error",
273
- message: "Failed to parse bootstrap result",
274
- error: "Invalid JSON response"
275
- };
276
- }
277
- isWorkerRunning() {
278
- const symbols = this.ensureLoaded();
279
- return symbols.is_worker_running() === 1;
280
- }
281
- getWorkerStatus() {
282
- const symbols = this.ensureLoaded();
283
- const result = symbols.get_worker_status();
284
- const jsonStr = this.fromCString(result);
285
- if (result !== null) symbols.free_rust_string(result);
286
- const parsed = this.parseJson(jsonStr);
287
- return parsed ?? { success: false, running: false };
288
- }
289
- stopWorker() {
290
- const symbols = this.ensureLoaded();
291
- const result = symbols.stop_worker();
292
- const jsonStr = this.fromCString(result);
293
- if (result !== null) symbols.free_rust_string(result);
294
- const parsed = this.parseJson(jsonStr);
295
- return parsed ?? {
296
- success: false,
297
- status: "error",
298
- message: "Failed to parse stop result",
299
- error: "Invalid JSON response"
300
- };
301
- }
302
- transitionToGracefulShutdown() {
303
- const symbols = this.ensureLoaded();
304
- const result = symbols.transition_to_graceful_shutdown();
305
- const jsonStr = this.fromCString(result);
306
- if (result !== null) symbols.free_rust_string(result);
307
- const parsed = this.parseJson(jsonStr);
308
- return parsed ?? {
309
- success: false,
310
- status: "error",
311
- message: "Failed to parse shutdown result",
312
- error: "Invalid JSON response"
313
- };
314
- }
315
- pollStepEvents() {
316
- const symbols = this.ensureLoaded();
317
- const result = symbols.poll_step_events();
318
- if (result === null || Deno.UnsafePointer.equals(result, null)) {
319
- return null;
320
- }
321
- const jsonStr = this.fromCString(result);
322
- symbols.free_rust_string(result);
323
- return this.parseJson(jsonStr);
324
- }
325
- pollInProcessEvents() {
326
- const symbols = this.ensureLoaded();
327
- const result = symbols.poll_in_process_events();
328
- if (result === null || Deno.UnsafePointer.equals(result, null)) {
329
- return null;
330
- }
331
- const jsonStr = this.fromCString(result);
332
- symbols.free_rust_string(result);
333
- return this.parseJson(jsonStr);
334
- }
335
- completeStepEvent(eventId, result) {
336
- const symbols = this.ensureLoaded();
337
- const eventIdBuf = this.toCString(eventId);
338
- const resultJsonBuf = this.toCString(this.toJson(result));
339
- return symbols.complete_step_event(eventIdBuf, resultJsonBuf) === 1;
340
- }
341
- checkpointYieldStepEvent(eventId, checkpointData) {
342
- const symbols = this.ensureLoaded();
343
- const eventIdBuf = this.toCString(eventId);
344
- const checkpointJsonBuf = this.toCString(this.toJson(checkpointData));
345
- return symbols.checkpoint_yield_step_event(eventIdBuf, checkpointJsonBuf) === 1;
346
- }
347
- getFfiDispatchMetrics() {
348
- const symbols = this.ensureLoaded();
349
- const result = symbols.get_ffi_dispatch_metrics();
350
- const jsonStr = this.fromCString(result);
351
- if (result !== null) symbols.free_rust_string(result);
352
- const parsed = this.parseJson(jsonStr);
353
- if (parsed && typeof parsed.pending_count === "number") {
354
- return parsed;
355
- }
356
- return {
357
- pending_count: 0,
358
- starvation_detected: false,
359
- starving_event_count: 0,
360
- oldest_pending_age_ms: null,
361
- newest_pending_age_ms: null,
362
- oldest_event_id: null
363
- };
364
- }
365
- checkStarvationWarnings() {
366
- const symbols = this.ensureLoaded();
367
- symbols.check_starvation_warnings();
368
- }
369
- cleanupTimeouts() {
370
- const symbols = this.ensureLoaded();
371
- symbols.cleanup_timeouts();
372
- }
373
- logError(message, fields) {
374
- const symbols = this.ensureLoaded();
375
- const msgBuf = this.toCString(message);
376
- const fieldsBuf = fields ? this.toCString(this.toJson(fields)) : null;
377
- symbols.log_error(msgBuf, fieldsBuf);
378
- }
379
- logWarn(message, fields) {
380
- const symbols = this.ensureLoaded();
381
- const msgBuf = this.toCString(message);
382
- const fieldsBuf = fields ? this.toCString(this.toJson(fields)) : null;
383
- symbols.log_warn(msgBuf, fieldsBuf);
384
- }
385
- logInfo(message, fields) {
386
- const symbols = this.ensureLoaded();
387
- const msgBuf = this.toCString(message);
388
- const fieldsBuf = fields ? this.toCString(this.toJson(fields)) : null;
389
- symbols.log_info(msgBuf, fieldsBuf);
390
- }
391
- logDebug(message, fields) {
392
- const symbols = this.ensureLoaded();
393
- const msgBuf = this.toCString(message);
394
- const fieldsBuf = fields ? this.toCString(this.toJson(fields)) : null;
395
- symbols.log_debug(msgBuf, fieldsBuf);
396
- }
397
- logTrace(message, fields) {
398
- const symbols = this.ensureLoaded();
399
- const msgBuf = this.toCString(message);
400
- const fieldsBuf = fields ? this.toCString(this.toJson(fields)) : null;
401
- symbols.log_trace(msgBuf, fieldsBuf);
402
- }
403
- // ==========================================================================
404
- // Client API Operations (TAS-231)
405
- // ==========================================================================
406
- parseClientResult(result) {
407
- const jsonStr = this.fromCString(result);
408
- if (result !== null) this.ensureLoaded().free_rust_string(result);
409
- const parsed = this.parseJson(jsonStr);
410
- return parsed ?? {
411
- success: false,
412
- data: null,
413
- error: "Failed to parse client result",
414
- recoverable: null
415
- };
416
- }
417
- clientCreateTask(requestJson) {
418
- const symbols = this.ensureLoaded();
419
- const buf = this.toCString(requestJson);
420
- const result = symbols.client_create_task(buf);
421
- return this.parseClientResult(result);
422
- }
423
- clientGetTask(taskUuid) {
424
- const symbols = this.ensureLoaded();
425
- const buf = this.toCString(taskUuid);
426
- const result = symbols.client_get_task(buf);
427
- return this.parseClientResult(result);
428
- }
429
- clientListTasks(paramsJson) {
430
- const symbols = this.ensureLoaded();
431
- const buf = this.toCString(paramsJson);
432
- const result = symbols.client_list_tasks(buf);
433
- return this.parseClientResult(result);
434
- }
435
- clientCancelTask(taskUuid) {
436
- const symbols = this.ensureLoaded();
437
- const buf = this.toCString(taskUuid);
438
- const result = symbols.client_cancel_task(buf);
439
- return this.parseClientResult(result);
440
- }
441
- clientListTaskSteps(taskUuid) {
442
- const symbols = this.ensureLoaded();
443
- const buf = this.toCString(taskUuid);
444
- const result = symbols.client_list_task_steps(buf);
445
- return this.parseClientResult(result);
446
- }
447
- clientGetStep(taskUuid, stepUuid) {
448
- const symbols = this.ensureLoaded();
449
- const tBuf = this.toCString(taskUuid);
450
- const sBuf = this.toCString(stepUuid);
451
- const result = symbols.client_get_step(tBuf, sBuf);
452
- return this.parseClientResult(result);
453
- }
454
- clientGetStepAuditHistory(taskUuid, stepUuid) {
455
- const symbols = this.ensureLoaded();
456
- const tBuf = this.toCString(taskUuid);
457
- const sBuf = this.toCString(stepUuid);
458
- const result = symbols.client_get_step_audit_history(tBuf, sBuf);
459
- return this.parseClientResult(result);
460
- }
461
- clientHealthCheck() {
462
- const symbols = this.ensureLoaded();
463
- const result = symbols.client_health_check();
464
- return this.parseClientResult(result);
465
- }
466
- };
467
- }
468
- });
469
-
470
- // node_modules/koffi/build/koffi/darwin_arm64/koffi.node
471
- var koffi_default;
472
- var init_koffi = __esm({
473
- "node_modules/koffi/build/koffi/darwin_arm64/koffi.node"() {
474
- koffi_default = "./koffi-X7JMBSZH.node";
475
- }
476
- });
477
-
478
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/darwin_arm64/koffi.node
479
- var require_koffi = __commonJS2({
480
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/darwin_arm64/koffi.node"(exports2, module2) {
481
- init_koffi();
482
- try {
483
- module2.exports = __require(koffi_default);
484
- } catch {
485
- }
486
- }
487
- });
488
-
489
- // node_modules/koffi/build/koffi/darwin_x64/koffi.node
490
- var koffi_default2;
491
- var init_koffi2 = __esm({
492
- "node_modules/koffi/build/koffi/darwin_x64/koffi.node"() {
493
- koffi_default2 = "./koffi-OMHWL3D6.node";
494
- }
495
- });
496
-
497
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/darwin_x64/koffi.node
498
- var require_koffi2 = __commonJS2({
499
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/darwin_x64/koffi.node"(exports2, module2) {
500
- init_koffi2();
501
- try {
502
- module2.exports = __require(koffi_default2);
503
- } catch {
504
- }
505
- }
506
- });
507
-
508
- // node_modules/koffi/build/koffi/freebsd_arm64/koffi.node
509
- var koffi_default3;
510
- var init_koffi3 = __esm({
511
- "node_modules/koffi/build/koffi/freebsd_arm64/koffi.node"() {
512
- koffi_default3 = "./koffi-AVDVVSXH.node";
513
- }
514
- });
515
-
516
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/freebsd_arm64/koffi.node
517
- var require_koffi3 = __commonJS2({
518
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/freebsd_arm64/koffi.node"(exports2, module2) {
519
- init_koffi3();
520
- try {
521
- module2.exports = __require(koffi_default3);
522
- } catch {
523
- }
524
- }
525
- });
526
-
527
- // node_modules/koffi/build/koffi/freebsd_ia32/koffi.node
528
- var koffi_default4;
529
- var init_koffi4 = __esm({
530
- "node_modules/koffi/build/koffi/freebsd_ia32/koffi.node"() {
531
- koffi_default4 = "./koffi-GG4SDSYA.node";
532
- }
533
- });
534
-
535
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/freebsd_ia32/koffi.node
536
- var require_koffi4 = __commonJS2({
537
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/freebsd_ia32/koffi.node"(exports2, module2) {
538
- init_koffi4();
539
- try {
540
- module2.exports = __require(koffi_default4);
541
- } catch {
542
- }
543
- }
544
- });
545
-
546
- // node_modules/koffi/build/koffi/freebsd_x64/koffi.node
547
- var koffi_default5;
548
- var init_koffi5 = __esm({
549
- "node_modules/koffi/build/koffi/freebsd_x64/koffi.node"() {
550
- koffi_default5 = "./koffi-AHHUCM3C.node";
551
- }
552
- });
553
-
554
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/freebsd_x64/koffi.node
555
- var require_koffi5 = __commonJS2({
556
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/freebsd_x64/koffi.node"(exports2, module2) {
557
- init_koffi5();
558
- try {
559
- module2.exports = __require(koffi_default5);
560
- } catch {
561
- }
562
- }
563
- });
564
-
565
- // node_modules/koffi/build/koffi/linux_armhf/koffi.node
566
- var koffi_default6;
567
- var init_koffi6 = __esm({
568
- "node_modules/koffi/build/koffi/linux_armhf/koffi.node"() {
569
- koffi_default6 = "./koffi-YNQDUF3Q.node";
570
- }
571
- });
572
-
573
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_armhf/koffi.node
574
- var require_koffi6 = __commonJS2({
575
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_armhf/koffi.node"(exports2, module2) {
576
- init_koffi6();
577
- try {
578
- module2.exports = __require(koffi_default6);
579
- } catch {
580
- }
581
- }
582
- });
583
-
584
- // node_modules/koffi/build/koffi/linux_arm64/koffi.node
585
- var koffi_default7;
586
- var init_koffi7 = __esm({
587
- "node_modules/koffi/build/koffi/linux_arm64/koffi.node"() {
588
- koffi_default7 = "./koffi-SE4ZI36U.node";
589
- }
590
- });
591
-
592
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_arm64/koffi.node
593
- var require_koffi7 = __commonJS2({
594
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_arm64/koffi.node"(exports2, module2) {
595
- init_koffi7();
596
- try {
597
- module2.exports = __require(koffi_default7);
598
- } catch {
599
- }
600
- }
601
- });
602
-
603
- // node_modules/koffi/build/koffi/linux_ia32/koffi.node
604
- var koffi_default8;
605
- var init_koffi8 = __esm({
606
- "node_modules/koffi/build/koffi/linux_ia32/koffi.node"() {
607
- koffi_default8 = "./koffi-LOH6WKRQ.node";
608
- }
609
- });
610
-
611
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_ia32/koffi.node
612
- var require_koffi8 = __commonJS2({
613
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_ia32/koffi.node"(exports2, module2) {
614
- init_koffi8();
615
- try {
616
- module2.exports = __require(koffi_default8);
617
- } catch {
618
- }
619
- }
620
- });
621
-
622
- // node_modules/koffi/build/koffi/linux_loong64/koffi.node
623
- var koffi_default9;
624
- var init_koffi9 = __esm({
625
- "node_modules/koffi/build/koffi/linux_loong64/koffi.node"() {
626
- koffi_default9 = "./koffi-QKY2KSXW.node";
627
- }
628
- });
629
-
630
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_loong64/koffi.node
631
- var require_koffi9 = __commonJS2({
632
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_loong64/koffi.node"(exports2, module2) {
633
- init_koffi9();
634
- try {
635
- module2.exports = __require(koffi_default9);
636
- } catch {
637
- }
638
- }
639
- });
640
-
641
- // node_modules/koffi/build/koffi/linux_riscv64d/koffi.node
642
- var koffi_default10;
643
- var init_koffi10 = __esm({
644
- "node_modules/koffi/build/koffi/linux_riscv64d/koffi.node"() {
645
- koffi_default10 = "./koffi-X3YT67KE.node";
646
- }
647
- });
648
-
649
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_riscv64d/koffi.node
650
- var require_koffi10 = __commonJS2({
651
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_riscv64d/koffi.node"(exports2, module2) {
652
- init_koffi10();
653
- try {
654
- module2.exports = __require(koffi_default10);
655
- } catch {
656
- }
657
- }
658
- });
659
-
660
- // node_modules/koffi/build/koffi/linux_x64/koffi.node
661
- var koffi_default11;
662
- var init_koffi11 = __esm({
663
- "node_modules/koffi/build/koffi/linux_x64/koffi.node"() {
664
- koffi_default11 = "./koffi-G4D35B2D.node";
665
- }
666
- });
667
-
668
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_x64/koffi.node
669
- var require_koffi11 = __commonJS2({
670
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/linux_x64/koffi.node"(exports2, module2) {
671
- init_koffi11();
672
- try {
673
- module2.exports = __require(koffi_default11);
674
- } catch {
675
- }
676
- }
677
- });
678
-
679
- // node_modules/koffi/build/koffi/openbsd_ia32/koffi.node
680
- var koffi_default12;
681
- var init_koffi12 = __esm({
682
- "node_modules/koffi/build/koffi/openbsd_ia32/koffi.node"() {
683
- koffi_default12 = "./koffi-LUY2JHJP.node";
684
- }
685
- });
686
-
687
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/openbsd_ia32/koffi.node
688
- var require_koffi12 = __commonJS2({
689
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/openbsd_ia32/koffi.node"(exports2, module2) {
690
- init_koffi12();
691
- try {
692
- module2.exports = __require(koffi_default12);
693
- } catch {
694
- }
695
- }
696
- });
697
-
698
- // node_modules/koffi/build/koffi/openbsd_x64/koffi.node
699
- var koffi_default13;
700
- var init_koffi13 = __esm({
701
- "node_modules/koffi/build/koffi/openbsd_x64/koffi.node"() {
702
- koffi_default13 = "./koffi-ROB3FRHA.node";
703
- }
704
- });
705
-
706
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/openbsd_x64/koffi.node
707
- var require_koffi13 = __commonJS2({
708
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/openbsd_x64/koffi.node"(exports2, module2) {
709
- init_koffi13();
710
- try {
711
- module2.exports = __require(koffi_default13);
712
- } catch {
713
- }
714
- }
715
- });
716
-
717
- // node_modules/koffi/build/koffi/win32_arm64/koffi.node
718
- var koffi_default14;
719
- var init_koffi14 = __esm({
720
- "node_modules/koffi/build/koffi/win32_arm64/koffi.node"() {
721
- koffi_default14 = "./koffi-GOENU54R.node";
722
- }
723
- });
724
-
725
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/win32_arm64/koffi.node
726
- var require_koffi14 = __commonJS2({
727
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/win32_arm64/koffi.node"(exports2, module2) {
728
- init_koffi14();
729
- try {
730
- module2.exports = __require(koffi_default14);
731
- } catch {
732
- }
733
- }
734
- });
735
-
736
- // node_modules/koffi/build/koffi/win32_ia32/koffi.node
737
- var koffi_default15;
738
- var init_koffi15 = __esm({
739
- "node_modules/koffi/build/koffi/win32_ia32/koffi.node"() {
740
- koffi_default15 = "./koffi-KFZAXWPQ.node";
741
- }
742
- });
743
-
744
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/win32_ia32/koffi.node
745
- var require_koffi15 = __commonJS2({
746
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/win32_ia32/koffi.node"(exports2, module2) {
747
- init_koffi15();
748
- try {
749
- module2.exports = __require(koffi_default15);
750
- } catch {
751
- }
752
- }
753
- });
754
-
755
- // node_modules/koffi/build/koffi/win32_x64/koffi.node
756
- var koffi_default16;
757
- var init_koffi16 = __esm({
758
- "node_modules/koffi/build/koffi/win32_x64/koffi.node"() {
759
- koffi_default16 = "./koffi-IDX6JEDH.node";
760
- }
761
- });
762
-
763
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/win32_x64/koffi.node
764
- var require_koffi16 = __commonJS2({
765
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/win32_x64/koffi.node"(exports2, module2) {
766
- init_koffi16();
767
- try {
768
- module2.exports = __require(koffi_default16);
769
- } catch {
770
- }
771
- }
772
- });
773
-
774
- // node_modules/koffi/build/koffi/musl_arm64/koffi.node
775
- var koffi_default17;
776
- var init_koffi17 = __esm({
777
- "node_modules/koffi/build/koffi/musl_arm64/koffi.node"() {
778
- koffi_default17 = "./koffi-3HFAASOB.node";
779
- }
780
- });
781
-
782
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/musl_arm64/koffi.node
783
- var require_koffi17 = __commonJS2({
784
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/musl_arm64/koffi.node"(exports2, module2) {
785
- init_koffi17();
786
- try {
787
- module2.exports = __require(koffi_default17);
788
- } catch {
789
- }
790
- }
791
- });
792
-
793
- // node_modules/koffi/build/koffi/musl_x64/koffi.node
794
- var koffi_default18;
795
- var init_koffi18 = __esm({
796
- "node_modules/koffi/build/koffi/musl_x64/koffi.node"() {
797
- koffi_default18 = "./koffi-BMO5K7B3.node";
798
- }
799
- });
800
-
801
- // node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/musl_x64/koffi.node
802
- var require_koffi18 = __commonJS2({
803
- "node-file:/home/runner/work/tasker-core/tasker-core/workers/typescript/node_modules/koffi/build/koffi/musl_x64/koffi.node"(exports2, module2) {
804
- init_koffi18();
805
- try {
806
- module2.exports = __require(koffi_default18);
807
- } catch {
808
- }
809
- }
810
- });
811
-
812
- // node_modules/koffi/index.js
813
- var require_koffi19 = __commonJS2({
814
- "node_modules/koffi/index.js"(exports$1, module) {
815
- var __getOwnPropNames = Object.getOwnPropertyNames;
816
- var __commonJS = (cb, mod3) => function __require2() {
817
- return mod3 || (0, cb[__getOwnPropNames(cb)[0]])((mod3 = { exports: {} }).exports, mod3), mod3.exports;
818
- };
819
- var require_tools = __commonJS({
820
- "bin/Koffi/package/src/cnoke/src/tools.js"(exports2, module2) {
821
- var crypto2 = __require("crypto");
822
- var fs2 = __require("fs");
823
- var http = __require("https");
824
- var path2 = __require("path");
825
- var zlib = __require("zlib");
826
- async function download_http(url, dest) {
827
- console.log(">> Downloading " + url);
828
- let [tmp_name, file] = open_temporary_stream(dest);
829
- try {
830
- await new Promise((resolve, reject) => {
831
- let request = http.get(url, (response) => {
832
- if (response.statusCode != 200) {
833
- let err = new Error(`Download failed: ${response.statusMessage} [${response.statusCode}]`);
834
- err.code = response.statusCode;
835
- reject(err);
836
- return;
837
- }
838
- response.pipe(file);
839
- file.on("finish", () => file.close(() => {
840
- try {
841
- fs2.renameSync(file.path, dest);
842
- } catch (err) {
843
- if (!fs2.existsSync(dest))
844
- reject(err);
845
- }
846
- resolve();
847
- }));
848
- });
849
- request.on("error", reject);
850
- file.on("error", reject);
851
- });
852
- } catch (err) {
853
- file.close();
854
- try {
855
- fs2.unlinkSync(tmp_name);
856
- } catch (err2) {
857
- if (err2.code != "ENOENT")
858
- throw err2;
859
- }
860
- throw err;
861
- }
862
- }
863
- function open_temporary_stream(prefix) {
864
- let buf = Buffer.allocUnsafe(4);
865
- for (; ; ) {
866
- try {
867
- crypto2.randomFillSync(buf);
868
- let suffix = buf.toString("hex").padStart(8, "0");
869
- let filename2 = `${prefix}.${suffix}`;
870
- let file = fs2.createWriteStream(filename2, { flags: "wx", mode: 420 });
871
- return [filename2, file];
872
- } catch (err) {
873
- if (err.code != "EEXIST")
874
- throw err;
875
- }
876
- }
877
- }
878
- function extract_targz(filename2, dest_dir, strip = 0) {
879
- let reader = fs2.createReadStream(filename2).pipe(zlib.createGunzip());
880
- return new Promise((resolve, reject) => {
881
- let header = null;
882
- let extended = {};
883
- reader.on("readable", () => {
884
- try {
885
- for (; ; ) {
886
- if (header == null) {
887
- let buf = reader.read(512);
888
- if (buf == null)
889
- break;
890
- if (!buf[0])
891
- continue;
892
- header = {
893
- filename: buf.toString("utf-8", 0, 100).replace(/\0/g, ""),
894
- mode: parseInt(buf.toString("ascii", 100, 109), 8),
895
- size: parseInt(buf.toString("ascii", 124, 137), 8),
896
- type: String.fromCharCode(buf[156])
897
- };
898
- Object.assign(header, extended);
899
- extended = {};
900
- header.filename = header.filename.replace(/\\/g, "/");
901
- if (!header.filename.length)
902
- throw new Error(`Insecure empty filename inside TAR archive`);
903
- if (path_is_absolute(header.filename[0]))
904
- throw new Error(`Insecure filename starting with / inside TAR archive`);
905
- if (path_has_dotdot(header.filename))
906
- throw new Error(`Insecure filename containing '..' inside TAR archive`);
907
- for (let i = 0; i < strip; i++)
908
- header.filename = header.filename.substr(header.filename.indexOf("/") + 1);
909
- }
910
- let aligned = Math.floor((header.size + 511) / 512) * 512;
911
- let data = header.size ? reader.read(aligned) : null;
912
- if (data == null) {
913
- if (header.size)
914
- break;
915
- data = Buffer.alloc(0);
916
- }
917
- data = data.subarray(0, header.size);
918
- if (header.type == "0" || header.type == "7") {
919
- let filename3 = dest_dir + "/" + header.filename;
920
- let dirname2 = path2.dirname(filename3);
921
- fs2.mkdirSync(dirname2, { recursive: true, mode: 493 });
922
- fs2.writeFileSync(filename3, data, { mode: header.mode });
923
- } else if (header.type == "5") {
924
- let filename3 = dest_dir + "/" + header.filename;
925
- fs2.mkdirSync(filename3, { recursive: true, mode: header.mode });
926
- } else if (header.type == "L") {
927
- extended.filename = data.toString("utf-8").replace(/\0/g, "");
928
- } else if (header.type == "x") {
929
- let str = data.toString("utf-8");
930
- try {
931
- while (str.length) {
932
- let matches = str.match(/^([0-9]+) ([a-zA-Z0-9\._]+)=(.*)\n/);
933
- let skip = parseInt(matches[1], 10);
934
- let key = matches[2];
935
- let value = matches[3];
936
- switch (key) {
937
- case "path":
938
- {
939
- extended.filename = value;
940
- }
941
- break;
942
- case "size":
943
- {
944
- extended.size = parseInt(value, 10);
945
- }
946
- break;
947
- }
948
- str = str.substr(skip).trimStart();
949
- }
950
- } catch (err) {
951
- throw new Error("Malformed PAX entry");
952
- }
953
- }
954
- header = null;
955
- }
956
- } catch (err) {
957
- reject(err);
958
- }
959
- });
960
- reader.on("error", reject);
961
- reader.on("end", resolve);
962
- });
963
- }
964
- function path_is_absolute(path3) {
965
- if (process.platform == "win32" && path3.match(/^[a-zA-Z]:/))
966
- path3 = path3.substr(2);
967
- return is_path_separator(path3[0]);
968
- }
969
- function path_has_dotdot(path3) {
970
- let start = 0;
971
- for (; ; ) {
972
- let offset = path3.indexOf("..", start);
973
- if (offset < 0)
974
- break;
975
- start = offset + 2;
976
- if (offset && !is_path_separator(path3[offset - 1]))
977
- continue;
978
- if (offset + 2 < path3.length && !is_path_separator(path3[offset + 2]))
979
- continue;
980
- return true;
981
- }
982
- return false;
983
- }
984
- function is_path_separator(c) {
985
- if (c == "/")
986
- return true;
987
- if (process.platform == "win32" && c == "\\")
988
- return true;
989
- return false;
990
- }
991
- function sync_files(src_dir, dest_dir) {
992
- let keep = /* @__PURE__ */ new Set();
993
- {
994
- let entries = fs2.readdirSync(src_dir, { withFileTypes: true });
995
- for (let entry of entries) {
996
- if (!entry.isFile())
997
- continue;
998
- keep.add(entry.name);
999
- fs2.copyFileSync(src_dir + `/${entry.name}`, dest_dir + `/${entry.name}`);
1000
- }
1001
- }
1002
- {
1003
- let entries = fs2.readdirSync(dest_dir, { withFileTypes: true });
1004
- for (let entry of entries) {
1005
- if (!entry.isFile())
1006
- continue;
1007
- if (keep.has(entry.name))
1008
- continue;
1009
- fs2.unlinkSync(dest_dir + `/${entry.name}`);
1010
- }
1011
- }
1012
- }
1013
- function determine_arch2() {
1014
- let arch = process.arch;
1015
- if (arch == "riscv32" || arch == "riscv64") {
1016
- let buf = read_file_header(process.execPath, 512);
1017
- let header = decode_elf_header(buf);
1018
- let float_abi = header.e_flags & 6;
1019
- switch (float_abi) {
1020
- case 0:
1021
- break;
1022
- case 2:
1023
- {
1024
- arch += "f";
1025
- }
1026
- break;
1027
- case 4:
1028
- {
1029
- arch += "d";
1030
- }
1031
- break;
1032
- case 6:
1033
- {
1034
- arch += "q";
1035
- }
1036
- break;
1037
- }
1038
- } else if (arch == "arm") {
1039
- let buf = read_file_header(process.execPath, 512);
1040
- let header = decode_elf_header(buf);
1041
- if (header.e_flags & 1024) {
1042
- arch += "hf";
1043
- } else if (header.e_flags & 512) {
1044
- arch += "sf";
1045
- } else {
1046
- throw new Error("Unknown ARM floating-point ABI");
1047
- }
1048
- }
1049
- return arch;
1050
- }
1051
- function read_file_header(filename2, read) {
1052
- try {
1053
- let fd2 = fs2.openSync(filename2);
1054
- let buf = Buffer.allocUnsafe(read);
1055
- let len = fs2.readSync(fd2, buf);
1056
- return buf.subarray(0, len);
1057
- } finally {
1058
- }
1059
- }
1060
- function decode_elf_header(buf) {
1061
- let header = {};
1062
- if (buf.length < 16)
1063
- throw new Error("Truncated header");
1064
- if (buf[0] != 127 || buf[1] != 69 || buf[2] != 76 || buf[3] != 70)
1065
- throw new Error("Invalid magic number");
1066
- if (buf[6] != 1)
1067
- throw new Error("Invalid ELF version");
1068
- if (buf[5] != 1)
1069
- throw new Error("Big-endian architectures are not supported");
1070
- let machine = buf.readUInt16LE(18);
1071
- switch (machine) {
1072
- case 3:
1073
- {
1074
- header.e_machine = "ia32";
1075
- }
1076
- break;
1077
- case 40:
1078
- {
1079
- header.e_machine = "arm";
1080
- }
1081
- break;
1082
- case 62:
1083
- {
1084
- header.e_machine = "amd64";
1085
- }
1086
- break;
1087
- case 183:
1088
- {
1089
- header.e_machine = "arm64";
1090
- }
1091
- break;
1092
- case 243:
1093
- {
1094
- switch (buf[4]) {
1095
- case 1:
1096
- {
1097
- header.e_machine = "riscv32";
1098
- }
1099
- break;
1100
- case 2:
1101
- {
1102
- header.e_machine = "riscv64";
1103
- }
1104
- break;
1105
- }
1106
- }
1107
- break;
1108
- case 248:
1109
- {
1110
- switch (buf[4]) {
1111
- case 1:
1112
- {
1113
- header.e_machine = "loong32";
1114
- }
1115
- break;
1116
- case 2:
1117
- {
1118
- header.e_machine = "loong64";
1119
- }
1120
- break;
1121
- }
1122
- }
1123
- break;
1124
- default:
1125
- throw new Error("Unknown ELF machine type");
1126
- }
1127
- switch (buf[4]) {
1128
- case 1:
1129
- {
1130
- buf = buf.subarray(0, 68);
1131
- if (buf.length < 68)
1132
- throw new Error("Truncated ELF header");
1133
- header.ei_class = 32;
1134
- header.e_flags = buf.readUInt32LE(36);
1135
- }
1136
- break;
1137
- case 2:
1138
- {
1139
- buf = buf.subarray(0, 120);
1140
- if (buf.length < 120)
1141
- throw new Error("Truncated ELF header");
1142
- header.ei_class = 64;
1143
- header.e_flags = buf.readUInt32LE(48);
1144
- }
1145
- break;
1146
- default:
1147
- throw new Error("Invalid ELF class");
1148
- }
1149
- return header;
1150
- }
1151
- function unlink_recursive(path3) {
1152
- try {
1153
- if (fs2.rmSync != null) {
1154
- fs2.rmSync(path3, { recursive: true, maxRetries: process.platform == "win32" ? 3 : 0 });
1155
- } else {
1156
- fs2.rmdirSync(path3, { recursive: true, maxRetries: process.platform == "win32" ? 3 : 0 });
1157
- }
1158
- } catch (err) {
1159
- if (err.code !== "ENOENT")
1160
- throw err;
1161
- }
1162
- }
1163
- function get_napi_version2(napi, major) {
1164
- if (napi > 8)
1165
- return null;
1166
- const support = {
1167
- 6: ["6.14.2", "6.14.2", "6.14.2"],
1168
- 8: ["8.6.0", "8.10.0", "8.11.2"],
1169
- 9: ["9.0.0", "9.3.0", "9.11.0"],
1170
- 10: ["10.0.0", "10.0.0", "10.0.0", "10.16.0", "10.17.0", "10.20.0", "10.23.0"],
1171
- 11: ["11.0.0", "11.0.0", "11.0.0", "11.8.0"],
1172
- 12: ["12.0.0", "12.0.0", "12.0.0", "12.0.0", "12.11.0", "12.17.0", "12.19.0", "12.22.0"],
1173
- 13: ["13.0.0", "13.0.0", "13.0.0", "13.0.0", "13.0.0"],
1174
- 14: ["14.0.0", "14.0.0", "14.0.0", "14.0.0", "14.0.0", "14.0.0", "14.12.0", "14.17.0"],
1175
- 15: ["15.0.0", "15.0.0", "15.0.0", "15.0.0", "15.0.0", "15.0.0", "15.0.0", "15.12.0"]
1176
- };
1177
- const max = Math.max(...Object.keys(support).map((k) => parseInt(k, 10)));
1178
- if (major > max)
1179
- return major + ".0.0";
1180
- if (support[major] == null)
1181
- return null;
1182
- let required = support[major][napi - 1] || null;
1183
- return required;
1184
- }
1185
- function cmp_version(ver1, ver2) {
1186
- ver1 = String(ver1).replace(/-.*$/, "").split(".").reduce((acc, v, idx) => acc + parseInt(v, 10) * Math.pow(10, 2 * (5 - idx)), 0);
1187
- ver2 = String(ver2).replace(/-.*$/, "").split(".").reduce((acc, v, idx) => acc + parseInt(v, 10) * Math.pow(10, 2 * (5 - idx)), 0);
1188
- let cmp = Math.min(Math.max(ver1 - ver2, -1), 1);
1189
- return cmp;
1190
- }
1191
- module2.exports = {
1192
- download_http,
1193
- extract_targz,
1194
- path_is_absolute,
1195
- path_has_dotdot,
1196
- sync_files,
1197
- determine_arch: determine_arch2,
1198
- unlink_recursive,
1199
- get_napi_version: get_napi_version2,
1200
- cmp_version
1201
- };
1202
- }
1203
- });
1204
- var require_package = __commonJS({
1205
- "bin/Koffi/package/src/koffi/package.json"(exports2, module2) {
1206
- module2.exports = {
1207
- name: "koffi",
1208
- version: "2.15.0",
1209
- description: "Fast and simple C FFI (foreign function interface) for Node.js",
1210
- keywords: [
1211
- "foreign",
1212
- "function",
1213
- "interface",
1214
- "ffi",
1215
- "binding",
1216
- "c",
1217
- "napi"
1218
- ],
1219
- repository: {
1220
- type: "git",
1221
- url: "https://github.com/Koromix/koffi"
1222
- },
1223
- homepage: "https://koffi.dev/",
1224
- author: {
1225
- name: "Niels Martign\xE8ne",
1226
- email: "niels.martignene@protonmail.com",
1227
- url: "https://koromix.dev/"
1228
- },
1229
- main: "./index.js",
1230
- types: "./index.d.ts",
1231
- scripts: {
1232
- test: "node tools/koffi.js test",
1233
- prepack: `echo 'Use "npm run package" instead' && false`,
1234
- prepublishOnly: `echo 'Use "npm run package" instead' && false`,
1235
- package: "node tools/koffi.js build"
1236
- },
1237
- license: "MIT",
1238
- cnoke: {
1239
- api: "../../vendor/node-api-headers",
1240
- output: "../../bin/Koffi/{{ platform }}_{{ arch }}",
1241
- node: 16,
1242
- napi: 8,
1243
- require: "./index.js"
1244
- },
1245
- funding: "https://buymeacoffee.com/koromix"
1246
- };
1247
- }
1248
- });
1249
- var require_init = __commonJS({
1250
- "bin/Koffi/package/src/koffi/src/init.js"(exports$1, module) {
1251
- var fs = __require("fs");
1252
- var path = __require("path");
1253
- var util = __require("util");
1254
- var { get_napi_version, determine_arch } = require_tools();
1255
- var pkg = require_package();
1256
- function detect() {
1257
- if (process.versions.napi == null || process.versions.napi < pkg.cnoke.napi) {
1258
- let major = parseInt(process.versions.node, 10);
1259
- let required = get_napi_version(pkg.cnoke.napi, major);
1260
- if (required != null) {
1261
- throw new Error(`This engine is based on Node ${process.versions.node}, but ${pkg.name} requires Node >= ${required} in the Node ${major}.x branch (N-API >= ${pkg.cnoke.napi})`);
1262
- } else {
1263
- throw new Error(`This engine is based on Node ${process.versions.node}, but ${pkg.name} does not support the Node ${major}.x branch (N-API < ${pkg.cnoke.napi})`);
1264
- }
1265
- }
1266
- let arch = determine_arch();
1267
- let triplet3 = `${process.platform}_${arch}`;
1268
- return triplet3;
1269
- }
1270
- function init(triplet, native) {
1271
- if (native == null) {
1272
- let roots = [path.join(__dirname, "..")];
1273
- let triplets = [triplet];
1274
- if (process.resourcesPath != null)
1275
- roots.push(process.resourcesPath);
1276
- if (triplet.startsWith("linux_")) {
1277
- let musl = triplet.replace(/^linux_/, "musl_");
1278
- triplets.push(musl);
1279
- }
1280
- let filenames = roots.flatMap((root) => triplets.flatMap((triplet3) => [
1281
- `${root}/build/koffi/${triplet3}/koffi.node`,
1282
- `${root}/koffi/${triplet3}/koffi.node`,
1283
- `${root}/node_modules/koffi/build/koffi/${triplet3}/koffi.node`,
1284
- `${root}/../../bin/Koffi/${triplet3}/koffi.node`
1285
- ]));
1286
- let first_err = null;
1287
- for (let filename of filenames) {
1288
- if (!fs.existsSync(filename))
1289
- continue;
1290
- try {
1291
- native = eval("require")(filename);
1292
- } catch (err) {
1293
- if (first_err == null)
1294
- first_err = err;
1295
- continue;
1296
- }
1297
- break;
1298
- }
1299
- if (first_err != null)
1300
- throw first_err;
1301
- }
1302
- if (native == null)
1303
- throw new Error("Cannot find the native Koffi module; did you bundle it correctly?");
1304
- if (native.version != pkg.version)
1305
- throw new Error("Mismatched native Koffi modules");
1306
- let mod = wrap(native);
1307
- return mod;
1308
- }
1309
- function wrap(native3) {
1310
- let obj = {
1311
- ...native3,
1312
- // Deprecated functions
1313
- handle: util.deprecate(native3.opaque, "The koffi.handle() function was deprecated in Koffi 2.1, use koffi.opaque() instead", "KOFFI001"),
1314
- callback: util.deprecate(native3.proto, "The koffi.callback() function was deprecated in Koffi 2.4, use koffi.proto() instead", "KOFFI002")
1315
- };
1316
- obj.load = (...args) => {
1317
- let lib = native3.load(...args);
1318
- lib.cdecl = util.deprecate((...args2) => lib.func("__cdecl", ...args2), "The koffi.cdecl() function was deprecated in Koffi 2.7, use koffi.func(...) instead", "KOFFI003");
1319
- lib.stdcall = util.deprecate((...args2) => lib.func("__stdcall", ...args2), 'The koffi.stdcall() function was deprecated in Koffi 2.7, use koffi.func("__stdcall", ...) instead', "KOFFI004");
1320
- lib.fastcall = util.deprecate((...args2) => lib.func("__fastcall", ...args2), 'The koffi.fastcall() function was deprecated in Koffi 2.7, use koffi.func("__fastcall", ...) instead', "KOFFI005");
1321
- lib.thiscall = util.deprecate((...args2) => lib.func("__thiscall", ...args2), 'The koffi.thiscall() function was deprecated in Koffi 2.7, use koffi.func("__thiscall", ...) instead', "KOFFI006");
1322
- return lib;
1323
- };
1324
- return obj;
1325
- }
1326
- module.exports = {
1327
- detect,
1328
- init
1329
- };
1330
- }
1331
- });
1332
- var { detect: detect2, init: init2 } = require_init();
1333
- var triplet2 = detect2();
1334
- var native2 = null;
1335
- try {
1336
- switch (triplet2) {
1337
- case "darwin_arm64":
1338
- {
1339
- native2 = require_koffi();
1340
- }
1341
- break;
1342
- case "darwin_x64":
1343
- {
1344
- native2 = require_koffi2();
1345
- }
1346
- break;
1347
- case "freebsd_arm64":
1348
- {
1349
- native2 = require_koffi3();
1350
- }
1351
- break;
1352
- case "freebsd_ia32":
1353
- {
1354
- native2 = require_koffi4();
1355
- }
1356
- break;
1357
- case "freebsd_x64":
1358
- {
1359
- native2 = require_koffi5();
1360
- }
1361
- break;
1362
- case "linux_armhf":
1363
- {
1364
- native2 = require_koffi6();
1365
- }
1366
- break;
1367
- case "linux_arm64":
1368
- {
1369
- native2 = require_koffi7();
1370
- }
1371
- break;
1372
- case "linux_ia32":
1373
- {
1374
- native2 = require_koffi8();
1375
- }
1376
- break;
1377
- case "linux_loong64":
1378
- {
1379
- native2 = require_koffi9();
1380
- }
1381
- break;
1382
- case "linux_riscv64d":
1383
- {
1384
- native2 = require_koffi10();
1385
- }
1386
- break;
1387
- case "linux_x64":
1388
- {
1389
- native2 = require_koffi11();
1390
- }
1391
- break;
1392
- case "openbsd_ia32":
1393
- {
1394
- native2 = require_koffi12();
1395
- }
1396
- break;
1397
- case "openbsd_x64":
1398
- {
1399
- native2 = require_koffi13();
1400
- }
1401
- break;
1402
- case "win32_arm64":
1403
- {
1404
- native2 = require_koffi14();
1405
- }
1406
- break;
1407
- case "win32_ia32":
1408
- {
1409
- native2 = require_koffi15();
1410
- }
1411
- break;
1412
- case "win32_x64":
1413
- {
1414
- native2 = require_koffi16();
1415
- }
1416
- break;
1417
- }
1418
- } catch {
1419
- try {
1420
- switch (triplet2) {
1421
- case "linux_arm64":
1422
- {
1423
- native2 = require_koffi17();
1424
- }
1425
- break;
1426
- case "linux_x64":
1427
- {
1428
- native2 = require_koffi18();
1429
- }
1430
- break;
1431
- }
1432
- } catch {
1433
- }
1434
- }
1435
- var mod2 = init2(triplet2, native2);
1436
- module.exports = mod2;
1437
- }
1438
- });
1439
-
1440
- // src/ffi/node-runtime.ts
1441
- var node_runtime_exports = {};
1442
- __export(node_runtime_exports, {
1443
- NodeRuntime: () => NodeRuntime
1444
- });
1445
- var NodeRuntime;
1446
- var init_node_runtime = __esm({
1447
- "src/ffi/node-runtime.ts"() {
1448
- init_runtime_interface();
1449
- NodeRuntime = class extends BaseTaskerRuntime {
1450
- name = "node";
1451
- lib = null;
1452
- // biome-ignore lint/suspicious/noExplicitAny: koffi module type
1453
- koffi = null;
1454
- get isLoaded() {
1455
- return this.lib !== null;
1456
- }
1457
- async load(libraryPath) {
1458
- if (this.lib !== null) {
1459
- return;
1460
- }
1461
- const koffiModule = await Promise.resolve().then(() => __toESM(require_koffi19()));
1462
- this.koffi = koffiModule.default ?? koffiModule;
1463
- const lib = this.koffi.load(libraryPath);
1464
- this.lib = {
1465
- get_version: lib.func("void* get_version()"),
1466
- get_rust_version: lib.func("void* get_rust_version()"),
1467
- health_check: lib.func("int health_check()"),
1468
- is_worker_running: lib.func("int is_worker_running()"),
1469
- bootstrap_worker: lib.func("void* bootstrap_worker(str)"),
1470
- get_worker_status: lib.func("void* get_worker_status()"),
1471
- stop_worker: lib.func("void* stop_worker()"),
1472
- transition_to_graceful_shutdown: lib.func("void* transition_to_graceful_shutdown()"),
1473
- poll_step_events: lib.func("void* poll_step_events()"),
1474
- poll_in_process_events: lib.func("void* poll_in_process_events()"),
1475
- complete_step_event: lib.func("int complete_step_event(str, str)"),
1476
- checkpoint_yield_step_event: lib.func("int checkpoint_yield_step_event(str, str)"),
1477
- get_ffi_dispatch_metrics: lib.func("void* get_ffi_dispatch_metrics()"),
1478
- check_starvation_warnings: lib.func("void check_starvation_warnings()"),
1479
- cleanup_timeouts: lib.func("void cleanup_timeouts()"),
1480
- log_error: lib.func("void log_error(str, str)"),
1481
- log_warn: lib.func("void log_warn(str, str)"),
1482
- log_info: lib.func("void log_info(str, str)"),
1483
- log_debug: lib.func("void log_debug(str, str)"),
1484
- log_trace: lib.func("void log_trace(str, str)"),
1485
- free_rust_string: lib.func("void free_rust_string(void*)"),
1486
- // Client API functions (TAS-231)
1487
- client_create_task: lib.func("void* client_create_task(str)"),
1488
- client_get_task: lib.func("void* client_get_task(str)"),
1489
- client_list_tasks: lib.func("void* client_list_tasks(str)"),
1490
- client_cancel_task: lib.func("void* client_cancel_task(str)"),
1491
- client_list_task_steps: lib.func("void* client_list_task_steps(str)"),
1492
- client_get_step: lib.func("void* client_get_step(str, str)"),
1493
- client_get_step_audit_history: lib.func("void* client_get_step_audit_history(str, str)"),
1494
- client_health_check: lib.func("void* client_health_check()")
1495
- };
1496
- }
1497
- unload() {
1498
- this.lib = null;
1499
- this.koffi = null;
1500
- }
1501
- ensureLoaded() {
1502
- if (!this.lib) {
1503
- throw new Error("Native library not loaded. Call load() first.");
1504
- }
1505
- return this.lib;
1506
- }
1507
- /**
1508
- * Read a C string from a pointer and free the Rust-allocated memory.
1509
- *
1510
- * Uses koffi.decode with 'char' type and -1 length for null-terminated strings.
1511
- */
1512
- readAndFreeRustString(ptr) {
1513
- if (!ptr) return null;
1514
- const lib = this.ensureLoaded();
1515
- const str = this.koffi.decode(ptr, "char", -1);
1516
- lib.free_rust_string(ptr);
1517
- return str;
1518
- }
1519
- getVersion() {
1520
- const lib = this.ensureLoaded();
1521
- const ptr = lib.get_version();
1522
- return this.readAndFreeRustString(ptr) ?? "unknown";
1523
- }
1524
- getRustVersion() {
1525
- const lib = this.ensureLoaded();
1526
- const ptr = lib.get_rust_version();
1527
- return this.readAndFreeRustString(ptr) ?? "unknown";
1528
- }
1529
- healthCheck() {
1530
- const lib = this.ensureLoaded();
1531
- return lib.health_check() === 1;
1532
- }
1533
- bootstrapWorker(config) {
1534
- const lib = this.ensureLoaded();
1535
- const configJson = config ? this.toJson(config) : null;
1536
- const ptr = lib.bootstrap_worker(configJson);
1537
- const jsonStr = this.readAndFreeRustString(ptr);
1538
- const parsed = this.parseJson(jsonStr);
1539
- return parsed ?? {
1540
- success: false,
1541
- status: "error",
1542
- message: "Failed to parse bootstrap result",
1543
- error: "Invalid JSON response"
1544
- };
1545
- }
1546
- isWorkerRunning() {
1547
- const lib = this.ensureLoaded();
1548
- return lib.is_worker_running() === 1;
1549
- }
1550
- getWorkerStatus() {
1551
- const lib = this.ensureLoaded();
1552
- const ptr = lib.get_worker_status();
1553
- const jsonStr = this.readAndFreeRustString(ptr);
1554
- const parsed = this.parseJson(jsonStr);
1555
- return parsed ?? { success: false, running: false };
1556
- }
1557
- stopWorker() {
1558
- const lib = this.ensureLoaded();
1559
- const ptr = lib.stop_worker();
1560
- const jsonStr = this.readAndFreeRustString(ptr);
1561
- const parsed = this.parseJson(jsonStr);
1562
- return parsed ?? {
1563
- success: false,
1564
- status: "error",
1565
- message: "Failed to parse stop result",
1566
- error: "Invalid JSON response"
1567
- };
1568
- }
1569
- transitionToGracefulShutdown() {
1570
- const lib = this.ensureLoaded();
1571
- const ptr = lib.transition_to_graceful_shutdown();
1572
- const jsonStr = this.readAndFreeRustString(ptr);
1573
- const parsed = this.parseJson(jsonStr);
1574
- return parsed ?? {
1575
- success: false,
1576
- status: "error",
1577
- message: "Failed to parse shutdown result",
1578
- error: "Invalid JSON response"
1579
- };
1580
- }
1581
- pollStepEvents() {
1582
- const lib = this.ensureLoaded();
1583
- const ptr = lib.poll_step_events();
1584
- if (!ptr) return null;
1585
- const jsonStr = this.readAndFreeRustString(ptr);
1586
- return this.parseJson(jsonStr);
1587
- }
1588
- pollInProcessEvents() {
1589
- const lib = this.ensureLoaded();
1590
- const ptr = lib.poll_in_process_events();
1591
- if (!ptr) return null;
1592
- const jsonStr = this.readAndFreeRustString(ptr);
1593
- return this.parseJson(jsonStr);
1594
- }
1595
- completeStepEvent(eventId, result) {
1596
- const lib = this.ensureLoaded();
1597
- return lib.complete_step_event(eventId, this.toJson(result)) === 1;
1598
- }
1599
- checkpointYieldStepEvent(eventId, checkpointData) {
1600
- const lib = this.ensureLoaded();
1601
- return lib.checkpoint_yield_step_event(eventId, this.toJson(checkpointData)) === 1;
1602
- }
1603
- getFfiDispatchMetrics() {
1604
- const lib = this.ensureLoaded();
1605
- const ptr = lib.get_ffi_dispatch_metrics();
1606
- const jsonStr = this.readAndFreeRustString(ptr);
1607
- const parsed = this.parseJson(jsonStr);
1608
- if (parsed && typeof parsed.pending_count === "number") {
1609
- return parsed;
1610
- }
1611
- return {
1612
- pending_count: 0,
1613
- starvation_detected: false,
1614
- starving_event_count: 0,
1615
- oldest_pending_age_ms: null,
1616
- newest_pending_age_ms: null,
1617
- oldest_event_id: null
1618
- };
1619
- }
1620
- checkStarvationWarnings() {
1621
- const lib = this.ensureLoaded();
1622
- lib.check_starvation_warnings();
1623
- }
1624
- cleanupTimeouts() {
1625
- const lib = this.ensureLoaded();
1626
- lib.cleanup_timeouts();
1627
- }
1628
- logError(message, fields) {
1629
- const lib = this.ensureLoaded();
1630
- lib.log_error(message, fields ? this.toJson(fields) : null);
1631
- }
1632
- logWarn(message, fields) {
1633
- const lib = this.ensureLoaded();
1634
- lib.log_warn(message, fields ? this.toJson(fields) : null);
1635
- }
1636
- logInfo(message, fields) {
1637
- const lib = this.ensureLoaded();
1638
- lib.log_info(message, fields ? this.toJson(fields) : null);
1639
- }
1640
- logDebug(message, fields) {
1641
- const lib = this.ensureLoaded();
1642
- lib.log_debug(message, fields ? this.toJson(fields) : null);
1643
- }
1644
- logTrace(message, fields) {
1645
- const lib = this.ensureLoaded();
1646
- lib.log_trace(message, fields ? this.toJson(fields) : null);
1647
- }
1648
- // ==========================================================================
1649
- // Client API Operations (TAS-231)
1650
- // ==========================================================================
1651
- parseClientResult(ptr) {
1652
- const jsonStr = this.readAndFreeRustString(ptr);
1653
- const parsed = this.parseJson(jsonStr);
1654
- return parsed ?? {
1655
- success: false,
1656
- data: null,
1657
- error: "Failed to parse client result",
1658
- recoverable: null
1659
- };
1660
- }
1661
- clientCreateTask(requestJson) {
1662
- const lib = this.ensureLoaded();
1663
- const ptr = lib.client_create_task(requestJson);
1664
- return this.parseClientResult(ptr);
1665
- }
1666
- clientGetTask(taskUuid) {
1667
- const lib = this.ensureLoaded();
1668
- const ptr = lib.client_get_task(taskUuid);
1669
- return this.parseClientResult(ptr);
1670
- }
1671
- clientListTasks(paramsJson) {
1672
- const lib = this.ensureLoaded();
1673
- const ptr = lib.client_list_tasks(paramsJson);
1674
- return this.parseClientResult(ptr);
1675
- }
1676
- clientCancelTask(taskUuid) {
1677
- const lib = this.ensureLoaded();
1678
- const ptr = lib.client_cancel_task(taskUuid);
1679
- return this.parseClientResult(ptr);
1680
- }
1681
- clientListTaskSteps(taskUuid) {
1682
- const lib = this.ensureLoaded();
1683
- const ptr = lib.client_list_task_steps(taskUuid);
1684
- return this.parseClientResult(ptr);
1685
- }
1686
- clientGetStep(taskUuid, stepUuid) {
1687
- const lib = this.ensureLoaded();
1688
- const ptr = lib.client_get_step(taskUuid, stepUuid);
1689
- return this.parseClientResult(ptr);
1690
- }
1691
- clientGetStepAuditHistory(taskUuid, stepUuid) {
1692
- const lib = this.ensureLoaded();
1693
- const ptr = lib.client_get_step_audit_history(taskUuid, stepUuid);
1694
- return this.parseClientResult(ptr);
1695
- }
1696
- clientHealthCheck() {
1697
- const lib = this.ensureLoaded();
1698
- const ptr = lib.client_health_check();
1699
- return this.parseClientResult(ptr);
1700
- }
1701
- };
1702
- }
1703
- });
1704
23
 
1705
24
  // src/registry/resolvers/explicit-mapping.ts
1706
25
  var explicit_mapping_exports = {};
@@ -1849,8 +168,8 @@ var init_class_lookup = __esm({
1849
168
  }
1850
169
  const modulePath = definition.callable;
1851
170
  try {
1852
- const module2 = await import(modulePath);
1853
- const handlerClass = this.findHandlerClass(module2);
171
+ const module = await import(modulePath);
172
+ const handlerClass = this.findHandlerClass(module);
1854
173
  if (!handlerClass) {
1855
174
  return null;
1856
175
  }
@@ -1866,11 +185,11 @@ var init_class_lookup = __esm({
1866
185
  /**
1867
186
  * Find a handler class in a module's exports.
1868
187
  */
1869
- findHandlerClass(module2) {
1870
- if (this.isHandlerClass(module2.default)) {
1871
- return module2.default;
188
+ findHandlerClass(module) {
189
+ if (this.isHandlerClass(module.default)) {
190
+ return module.default;
1872
191
  }
1873
- for (const [, exported] of Object.entries(module2)) {
192
+ for (const [, exported] of Object.entries(module)) {
1874
193
  if (this.isHandlerClass(exported)) {
1875
194
  return exported;
1876
195
  }
@@ -1904,96 +223,52 @@ function toFfiBootstrapConfig(config) {
1904
223
  return {};
1905
224
  }
1906
225
  const result = {};
1907
- if (config.workerId !== void 0) {
1908
- result.worker_id = config.workerId;
1909
- }
1910
- if (config.logLevel !== void 0) {
1911
- result.log_level = config.logLevel;
1912
- }
1913
- if (config.databaseUrl !== void 0) {
1914
- result.database_url = config.databaseUrl;
1915
- }
1916
- if (config.namespace !== void 0) {
1917
- result.namespace = config.namespace;
1918
- }
1919
- if (config.configPath !== void 0) {
1920
- result.config_path = config.configPath;
1921
- }
226
+ if (config.namespace !== void 0) result.namespace = config.namespace;
227
+ if (config.configPath !== void 0) result.configPath = config.configPath;
1922
228
  return result;
1923
229
  }
1924
230
  function fromFfiBootstrapResult(result) {
1925
- const converted = {
231
+ const out = {
1926
232
  success: result.success,
1927
233
  status: result.status,
1928
234
  message: result.message
1929
235
  };
1930
- if (result.worker_id !== void 0) {
1931
- converted.workerId = result.worker_id;
1932
- }
1933
- if (result.error !== void 0) {
1934
- converted.error = result.error;
1935
- }
1936
- return converted;
236
+ if (result.workerId != null) out.workerId = result.workerId;
237
+ return out;
1937
238
  }
1938
239
  function fromFfiWorkerStatus(status) {
1939
- const converted = {
240
+ const out = {
1940
241
  success: status.success,
1941
242
  running: status.running
1942
243
  };
1943
- if (status.status !== void 0) {
1944
- converted.status = status.status;
1945
- }
1946
- if (status.worker_id !== void 0) {
1947
- converted.workerId = status.worker_id;
1948
- }
1949
- if (status.environment !== void 0) {
1950
- converted.environment = status.environment;
1951
- }
1952
- if (status.worker_core_status !== void 0) {
1953
- converted.workerCoreStatus = status.worker_core_status;
1954
- }
1955
- if (status.web_api_enabled !== void 0) {
1956
- converted.webApiEnabled = status.web_api_enabled;
1957
- }
1958
- if (status.supported_namespaces !== void 0) {
1959
- converted.supportedNamespaces = status.supported_namespaces;
1960
- }
1961
- if (status.database_pool_size !== void 0) {
1962
- converted.databasePoolSize = status.database_pool_size;
1963
- }
1964
- if (status.database_pool_idle !== void 0) {
1965
- converted.databasePoolIdle = status.database_pool_idle;
1966
- }
1967
- return converted;
244
+ if (status.status != null) out.status = status.status;
245
+ if (status.workerId != null) out.workerId = status.workerId;
246
+ if (status.environment != null) out.environment = status.environment;
247
+ return out;
1968
248
  }
1969
249
  function fromFfiStopResult(result) {
1970
- const converted = {
250
+ const out = {
1971
251
  success: result.success,
1972
- status: result.status,
1973
- message: result.message
252
+ status: result.running ? "stopped" : "not_running",
253
+ message: result.status ?? "Worker stopped"
1974
254
  };
1975
- if (result.worker_id !== void 0) {
1976
- converted.workerId = result.worker_id;
1977
- }
1978
- if (result.error !== void 0) {
1979
- converted.error = result.error;
1980
- }
1981
- return converted;
255
+ if (result.workerId != null) out.workerId = result.workerId;
256
+ return out;
1982
257
  }
1983
258
 
1984
259
  // src/bootstrap/bootstrap.ts
1985
- async function bootstrapWorker(config, runtime) {
260
+ async function bootstrapWorker(config, module) {
1986
261
  try {
1987
- if (!runtime?.isLoaded) {
262
+ if (!module) {
1988
263
  return {
1989
264
  success: false,
1990
265
  status: "error",
1991
- message: "Runtime not loaded. Ensure the FFI library is available.",
1992
- error: "Runtime not loaded"
266
+ message: "Module not loaded. Ensure the FFI library is available.",
267
+ error: "Module not loaded"
1993
268
  };
1994
269
  }
1995
270
  const ffiConfig = toFfiBootstrapConfig(config);
1996
- const ffiResult = runtime.bootstrapWorker(ffiConfig);
271
+ const ffiResult = module.bootstrapWorker(ffiConfig);
1997
272
  return fromFfiBootstrapResult(ffiResult);
1998
273
  } catch (error) {
1999
274
  return {
@@ -2004,16 +279,16 @@ async function bootstrapWorker(config, runtime) {
2004
279
  };
2005
280
  }
2006
281
  }
2007
- function stopWorker(runtime) {
2008
- if (!runtime?.isLoaded) {
282
+ function stopWorker(module) {
283
+ if (!module) {
2009
284
  return {
2010
285
  success: true,
2011
286
  status: "not_running",
2012
- message: "Runtime not loaded"
287
+ message: "Module not loaded"
2013
288
  };
2014
289
  }
2015
290
  try {
2016
- const ffiResult = runtime.stopWorker();
291
+ const ffiResult = module.stopWorker();
2017
292
  return fromFfiStopResult(ffiResult);
2018
293
  } catch (error) {
2019
294
  return {
@@ -2024,8 +299,8 @@ function stopWorker(runtime) {
2024
299
  };
2025
300
  }
2026
301
  }
2027
- function getWorkerStatus(runtime) {
2028
- if (!runtime?.isLoaded) {
302
+ function getWorkerStatus(module) {
303
+ if (!module) {
2029
304
  return {
2030
305
  success: false,
2031
306
  running: false,
@@ -2033,7 +308,7 @@ function getWorkerStatus(runtime) {
2033
308
  };
2034
309
  }
2035
310
  try {
2036
- const ffiStatus = runtime.getWorkerStatus();
311
+ const ffiStatus = module.getWorkerStatus();
2037
312
  return fromFfiWorkerStatus(ffiStatus);
2038
313
  } catch (_error) {
2039
314
  return {
@@ -2043,16 +318,16 @@ function getWorkerStatus(runtime) {
2043
318
  };
2044
319
  }
2045
320
  }
2046
- function transitionToGracefulShutdown(runtime) {
2047
- if (!runtime?.isLoaded) {
321
+ function transitionToGracefulShutdown(module) {
322
+ if (!module) {
2048
323
  return {
2049
324
  success: true,
2050
325
  status: "not_running",
2051
- message: "Runtime not loaded"
326
+ message: "Module not loaded"
2052
327
  };
2053
328
  }
2054
329
  try {
2055
- const ffiResult = runtime.transitionToGracefulShutdown();
330
+ const ffiResult = module.transitionToGracefulShutdown();
2056
331
  return fromFfiStopResult(ffiResult);
2057
332
  } catch (error) {
2058
333
  return {
@@ -2063,42 +338,42 @@ function transitionToGracefulShutdown(runtime) {
2063
338
  };
2064
339
  }
2065
340
  }
2066
- function isWorkerRunning(runtime) {
2067
- if (!runtime?.isLoaded) {
341
+ function isWorkerRunning(module) {
342
+ if (!module) {
2068
343
  return false;
2069
344
  }
2070
345
  try {
2071
- return runtime.isWorkerRunning();
346
+ return module.isWorkerRunning();
2072
347
  } catch {
2073
348
  return false;
2074
349
  }
2075
350
  }
2076
- function getVersion(runtime) {
2077
- if (!runtime?.isLoaded) {
2078
- return "unknown (runtime not loaded)";
351
+ function getVersion(module) {
352
+ if (!module) {
353
+ return "unknown (module not loaded)";
2079
354
  }
2080
355
  try {
2081
- return runtime.getVersion();
356
+ return module.getVersion();
2082
357
  } catch {
2083
358
  return "unknown";
2084
359
  }
2085
360
  }
2086
- function getRustVersion(runtime) {
2087
- if (!runtime?.isLoaded) {
2088
- return "unknown (runtime not loaded)";
361
+ function getRustVersion(module) {
362
+ if (!module) {
363
+ return "unknown (module not loaded)";
2089
364
  }
2090
365
  try {
2091
- return runtime.getRustVersion();
366
+ return module.getRustVersion();
2092
367
  } catch {
2093
368
  return "unknown";
2094
369
  }
2095
370
  }
2096
- function healthCheck(runtime) {
2097
- if (!runtime?.isLoaded) {
371
+ function healthCheck(module) {
372
+ if (!module) {
2098
373
  return false;
2099
374
  }
2100
375
  try {
2101
- return runtime.healthCheck();
376
+ return module.healthCheck();
2102
377
  } catch {
2103
378
  return false;
2104
379
  }
@@ -2123,7 +398,7 @@ var TaskerClient = class {
2123
398
  * Create a task via the orchestration API.
2124
399
  *
2125
400
  * @param options - Task creation options (only `name` is required)
2126
- * @returns Typed task response
401
+ * @returns Typed task response data
2127
402
  * @throws TaskerClientError if the operation fails
2128
403
  */
2129
404
  createTask(options) {
@@ -2133,45 +408,45 @@ var TaskerClient = class {
2133
408
  version: options.version ?? "1.0.0",
2134
409
  context: options.context ?? {},
2135
410
  initiator: options.initiator ?? "tasker-core-typescript",
2136
- source_system: options.sourceSystem ?? "tasker-core",
411
+ sourceSystem: options.sourceSystem ?? "tasker-core",
2137
412
  reason: options.reason ?? "Task requested",
2138
- tags: options.tags ?? [],
2139
- requested_at: (/* @__PURE__ */ new Date()).toISOString(),
2140
- options: null,
2141
- priority: options.priority ?? null,
2142
- correlation_id: options.correlationId ?? crypto.randomUUID(),
2143
- parent_correlation_id: options.parentCorrelationId ?? null,
2144
- idempotency_key: options.idempotencyKey ?? null
413
+ tags: options.tags ?? []
2145
414
  };
2146
- const result = this.getRuntime().clientCreateTask(JSON.stringify(request));
415
+ if (options.priority !== void 0) request.priority = options.priority;
416
+ if (options.correlationId !== void 0) request.correlationId = options.correlationId;
417
+ else request.correlationId = crypto.randomUUID();
418
+ if (options.parentCorrelationId !== void 0)
419
+ request.parentCorrelationId = options.parentCorrelationId;
420
+ if (options.idempotencyKey !== void 0) request.idempotencyKey = options.idempotencyKey;
421
+ const result = this.getModule().clientCreateTask(request);
2147
422
  return this.unwrap(result);
2148
423
  }
2149
424
  /**
2150
425
  * Get a task by UUID.
2151
426
  *
2152
427
  * @param taskUuid - The task UUID
2153
- * @returns Typed task response
428
+ * @returns Typed task response data
2154
429
  * @throws TaskerClientError if the operation fails
2155
430
  */
2156
431
  getTask(taskUuid) {
2157
- const result = this.getRuntime().clientGetTask(taskUuid);
432
+ const result = this.getModule().clientGetTask(taskUuid);
2158
433
  return this.unwrap(result);
2159
434
  }
2160
435
  /**
2161
436
  * List tasks with optional filtering and pagination.
2162
437
  *
2163
438
  * @param options - Filtering and pagination options
2164
- * @returns Typed task list response with pagination
439
+ * @returns Typed task list response data
2165
440
  * @throws TaskerClientError if the operation fails
2166
441
  */
2167
442
  listTasks(options = {}) {
2168
443
  const params = {
2169
444
  limit: options.limit ?? 50,
2170
- offset: options.offset ?? 0,
2171
- namespace: options.namespace ?? null,
2172
- status: options.status ?? null
445
+ offset: options.offset ?? 0
2173
446
  };
2174
- const result = this.getRuntime().clientListTasks(JSON.stringify(params));
447
+ if (options.namespace !== void 0) params.namespace = options.namespace;
448
+ if (options.status !== void 0) params.status = options.status;
449
+ const result = this.getModule().clientListTasks(params);
2175
450
  return this.unwrap(result);
2176
451
  }
2177
452
  /**
@@ -2181,18 +456,18 @@ var TaskerClient = class {
2181
456
  * @throws TaskerClientError if the operation fails
2182
457
  */
2183
458
  cancelTask(taskUuid) {
2184
- const result = this.getRuntime().clientCancelTask(taskUuid);
459
+ const result = this.getModule().clientCancelTask(taskUuid);
2185
460
  this.unwrap(result);
2186
461
  }
2187
462
  /**
2188
463
  * List workflow steps for a task.
2189
464
  *
2190
465
  * @param taskUuid - The task UUID
2191
- * @returns Array of typed step responses
466
+ * @returns Array of step data
2192
467
  * @throws TaskerClientError if the operation fails
2193
468
  */
2194
469
  listTaskSteps(taskUuid) {
2195
- const result = this.getRuntime().clientListTaskSteps(taskUuid);
470
+ const result = this.getModule().clientListTaskSteps(taskUuid);
2196
471
  return this.unwrap(result);
2197
472
  }
2198
473
  /**
@@ -2200,11 +475,11 @@ var TaskerClient = class {
2200
475
  *
2201
476
  * @param taskUuid - The task UUID
2202
477
  * @param stepUuid - The step UUID
2203
- * @returns Typed step response
478
+ * @returns Typed step response data
2204
479
  * @throws TaskerClientError if the operation fails
2205
480
  */
2206
481
  getStep(taskUuid, stepUuid) {
2207
- const result = this.getRuntime().clientGetStep(taskUuid, stepUuid);
482
+ const result = this.getModule().clientGetStep(taskUuid, stepUuid);
2208
483
  return this.unwrap(result);
2209
484
  }
2210
485
  /**
@@ -2212,25 +487,25 @@ var TaskerClient = class {
2212
487
  *
2213
488
  * @param taskUuid - The task UUID
2214
489
  * @param stepUuid - The step UUID
2215
- * @returns Array of typed audit history entries
490
+ * @returns Array of audit history entries
2216
491
  * @throws TaskerClientError if the operation fails
2217
492
  */
2218
493
  getStepAuditHistory(taskUuid, stepUuid) {
2219
- const result = this.getRuntime().clientGetStepAuditHistory(taskUuid, stepUuid);
494
+ const result = this.getModule().clientGetStepAuditHistory(taskUuid, stepUuid);
2220
495
  return this.unwrap(result);
2221
496
  }
2222
497
  /**
2223
498
  * Check orchestration API health.
2224
499
  *
2225
- * @returns Typed health response
500
+ * @returns Typed health response data
2226
501
  * @throws TaskerClientError if the operation fails
2227
502
  */
2228
503
  healthCheck() {
2229
- const result = this.getRuntime().clientHealthCheck();
504
+ const result = this.getModule().clientHealthCheck();
2230
505
  return this.unwrap(result);
2231
506
  }
2232
507
  /**
2233
- * Unwrap a ClientResult envelope, throwing on error.
508
+ * Unwrap a NapiClientResult envelope, throwing on error.
2234
509
  */
2235
510
  unwrap(result) {
2236
511
  if (!result.success) {
@@ -2242,10 +517,10 @@ var TaskerClient = class {
2242
517
  return result.data;
2243
518
  }
2244
519
  /**
2245
- * Get the FFI runtime from the layer.
520
+ * Get the napi-rs module from the layer.
2246
521
  */
2247
- getRuntime() {
2248
- return this.ffiLayer.getRuntime();
522
+ getModule() {
523
+ return this.ffiLayer.getModule();
2249
524
  }
2250
525
  };
2251
526
 
@@ -2454,7 +729,7 @@ if (process.env.TASKER_ENV !== "production") {
2454
729
  }
2455
730
  var log = pino(loggerOptions);
2456
731
  var EventPoller = class {
2457
- runtime;
732
+ module;
2458
733
  config;
2459
734
  emitter;
2460
735
  state = "stopped";
@@ -2467,12 +742,12 @@ var EventPoller = class {
2467
742
  /**
2468
743
  * Create a new EventPoller.
2469
744
  *
2470
- * @param runtime - The FFI runtime for polling events
745
+ * @param module - The napi-rs module for polling events
2471
746
  * @param emitter - The event emitter to dispatch events to (required, no fallback)
2472
747
  * @param config - Optional configuration for polling behavior
2473
748
  */
2474
- constructor(runtime, emitter, config = {}) {
2475
- this.runtime = runtime;
749
+ constructor(module, emitter, config = {}) {
750
+ this.module = module;
2476
751
  this.emitter = emitter;
2477
752
  this.config = {
2478
753
  pollIntervalMs: config.pollIntervalMs ?? 10,
@@ -2539,13 +814,6 @@ var EventPoller = class {
2539
814
  log.debug({ component: "event-poller" }, "Already running, returning early");
2540
815
  return;
2541
816
  }
2542
- log.debug(
2543
- { component: "event-poller", runtimeLoaded: this.runtime.isLoaded },
2544
- "Checking runtime.isLoaded"
2545
- );
2546
- if (!this.runtime.isLoaded) {
2547
- throw new Error("Runtime not loaded. Call runtime.load() first.");
2548
- }
2549
817
  this.state = "running";
2550
818
  this.pollCount = 0;
2551
819
  this.cycleCount = 0;
@@ -2606,17 +874,17 @@ var EventPoller = class {
2606
874
  try {
2607
875
  let eventsProcessed = 0;
2608
876
  for (let i = 0; i < this.config.maxEventsPerCycle; i++) {
2609
- const event = this.runtime.pollStepEvents();
877
+ const event = this.module.pollStepEvents();
2610
878
  if (event === null) {
2611
879
  break;
2612
880
  }
2613
881
  eventsProcessed++;
2614
- const handlerCallable = event.step_definition.handler.callable;
882
+ const handlerCallable = event.stepDefinition.handlerCallable;
2615
883
  log.info(
2616
884
  {
2617
885
  component: "event-poller",
2618
886
  operation: "event_received",
2619
- stepUuid: event.step_uuid,
887
+ stepUuid: event.stepUuid,
2620
888
  handlerCallable,
2621
889
  eventIndex: i
2622
890
  },
@@ -2628,7 +896,7 @@ var EventPoller = class {
2628
896
  this.checkStarvation();
2629
897
  }
2630
898
  if (this.pollCount % this.config.cleanupInterval === 0) {
2631
- this.runtime.cleanupTimeouts();
899
+ this.module.cleanupTimeouts();
2632
900
  }
2633
901
  if (this.pollCount % this.config.metricsInterval === 0) {
2634
902
  this.emitMetrics();
@@ -2649,12 +917,12 @@ var EventPoller = class {
2649
917
  * Handle a step event
2650
918
  */
2651
919
  handleStepEvent(event) {
2652
- const handlerCallable = event.step_definition.handler.callable;
920
+ const handlerCallable = event.stepDefinition.handlerCallable;
2653
921
  log.debug(
2654
922
  {
2655
923
  component: "event-poller",
2656
924
  operation: "handle_step_event",
2657
- stepUuid: event.step_uuid,
925
+ stepUuid: event.stepUuid,
2658
926
  handlerCallable,
2659
927
  hasCallback: !!this.stepEventCallback
2660
928
  },
@@ -2665,7 +933,7 @@ var EventPoller = class {
2665
933
  {
2666
934
  component: "event-poller",
2667
935
  emitterInstanceId: this.emitter.getInstanceId(),
2668
- stepUuid: event.step_uuid,
936
+ stepUuid: event.stepUuid,
2669
937
  listenerCount: listenerCountBefore,
2670
938
  eventName: StepEventNames.STEP_EXECUTION_RECEIVED
2671
939
  },
@@ -2679,7 +947,7 @@ var EventPoller = class {
2679
947
  log.info(
2680
948
  {
2681
949
  component: "event-poller",
2682
- stepUuid: event.step_uuid,
950
+ stepUuid: event.stepUuid,
2683
951
  emitResult,
2684
952
  listenerCountAfter: this.emitter.listenerCount(StepEventNames.STEP_EXECUTION_RECEIVED),
2685
953
  eventName: StepEventNames.STEP_EXECUTION_RECEIVED
@@ -2690,7 +958,7 @@ var EventPoller = class {
2690
958
  log.error(
2691
959
  {
2692
960
  component: "event-poller",
2693
- stepUuid: event.step_uuid,
961
+ stepUuid: event.stepUuid,
2694
962
  error: emitError instanceof Error ? emitError.message : String(emitError),
2695
963
  stack: emitError instanceof Error ? emitError.stack : void 0
2696
964
  },
@@ -2699,7 +967,7 @@ var EventPoller = class {
2699
967
  }
2700
968
  if (this.stepEventCallback) {
2701
969
  log.debug(
2702
- { component: "event-poller", stepUuid: event.step_uuid },
970
+ { component: "event-poller", stepUuid: event.stepUuid },
2703
971
  "Invoking step event callback"
2704
972
  );
2705
973
  this.stepEventCallback(event).catch((error) => {
@@ -2707,7 +975,7 @@ var EventPoller = class {
2707
975
  });
2708
976
  } else {
2709
977
  log.warn(
2710
- { component: "event-poller", stepUuid: event.step_uuid },
978
+ { component: "event-poller", stepUuid: event.stepUuid },
2711
979
  "No step event callback registered!"
2712
980
  );
2713
981
  }
@@ -2717,9 +985,9 @@ var EventPoller = class {
2717
985
  */
2718
986
  checkStarvation() {
2719
987
  try {
2720
- this.runtime.checkStarvationWarnings();
2721
- const metrics = this.runtime.getFfiDispatchMetrics();
2722
- if (metrics.starvation_detected) {
988
+ this.module.checkStarvationWarnings();
989
+ const metrics = this.module.getFfiDispatchMetrics();
990
+ if (metrics.starvationDetected) {
2723
991
  this.emitter.emitStarvationDetected(metrics);
2724
992
  }
2725
993
  } catch (error) {
@@ -2731,7 +999,7 @@ var EventPoller = class {
2731
999
  */
2732
1000
  emitMetrics() {
2733
1001
  try {
2734
- const metrics = this.runtime.getFfiDispatchMetrics();
1002
+ const metrics = this.module.getFfiDispatchMetrics();
2735
1003
  this.emitter.emitMetricsUpdated(metrics);
2736
1004
  if (this.metricsCallback) {
2737
1005
  this.metricsCallback(metrics);
@@ -2756,20 +1024,17 @@ var EventPoller = class {
2756
1024
  }
2757
1025
  }
2758
1026
  };
2759
- function createEventPoller(runtime, emitter, config) {
2760
- return new EventPoller(runtime, emitter, config);
1027
+ function createEventPoller(module, emitter, config) {
1028
+ return new EventPoller(module, emitter, config);
2761
1029
  }
2762
1030
 
2763
1031
  // src/logging/index.ts
2764
- var installedRuntime = null;
2765
- function setLoggingRuntime(runtime) {
2766
- installedRuntime = runtime;
1032
+ var installedModule = null;
1033
+ function setLoggingRuntime(module) {
1034
+ installedModule = module;
2767
1035
  }
2768
- function getLoggingRuntime() {
2769
- if (installedRuntime?.isLoaded) {
2770
- return installedRuntime;
2771
- }
2772
- return null;
1036
+ function getLoggingModule() {
1037
+ return installedModule;
2773
1038
  }
2774
1039
  function toFfiFields(fields) {
2775
1040
  if (!fields) {
@@ -2789,61 +1054,61 @@ function fallbackLog(level, message, fields) {
2789
1054
  console.log(`[${timestamp}] ${level.toUpperCase()}: ${message}${fieldsStr}`);
2790
1055
  }
2791
1056
  function logError(message, fields) {
2792
- const runtime = getLoggingRuntime();
2793
- if (!runtime) {
1057
+ const module = getLoggingModule();
1058
+ if (!module) {
2794
1059
  fallbackLog("error", message, fields);
2795
1060
  return;
2796
1061
  }
2797
1062
  try {
2798
- runtime.logError(message, toFfiFields(fields));
1063
+ module.logError(message, toFfiFields(fields));
2799
1064
  } catch {
2800
1065
  fallbackLog("error", message, fields);
2801
1066
  }
2802
1067
  }
2803
1068
  function logWarn(message, fields) {
2804
- const runtime = getLoggingRuntime();
2805
- if (!runtime) {
1069
+ const module = getLoggingModule();
1070
+ if (!module) {
2806
1071
  fallbackLog("warn", message, fields);
2807
1072
  return;
2808
1073
  }
2809
1074
  try {
2810
- runtime.logWarn(message, toFfiFields(fields));
1075
+ module.logWarn(message, toFfiFields(fields));
2811
1076
  } catch {
2812
1077
  fallbackLog("warn", message, fields);
2813
1078
  }
2814
1079
  }
2815
1080
  function logInfo(message, fields) {
2816
- const runtime = getLoggingRuntime();
2817
- if (!runtime) {
1081
+ const module = getLoggingModule();
1082
+ if (!module) {
2818
1083
  fallbackLog("info", message, fields);
2819
1084
  return;
2820
1085
  }
2821
1086
  try {
2822
- runtime.logInfo(message, toFfiFields(fields));
1087
+ module.logInfo(message, toFfiFields(fields));
2823
1088
  } catch {
2824
1089
  fallbackLog("info", message, fields);
2825
1090
  }
2826
1091
  }
2827
1092
  function logDebug(message, fields) {
2828
- const runtime = getLoggingRuntime();
2829
- if (!runtime) {
1093
+ const module = getLoggingModule();
1094
+ if (!module) {
2830
1095
  fallbackLog("debug", message, fields);
2831
1096
  return;
2832
1097
  }
2833
1098
  try {
2834
- runtime.logDebug(message, toFfiFields(fields));
1099
+ module.logDebug(message, toFfiFields(fields));
2835
1100
  } catch {
2836
1101
  fallbackLog("debug", message, fields);
2837
1102
  }
2838
1103
  }
2839
1104
  function logTrace(message, fields) {
2840
- const runtime = getLoggingRuntime();
2841
- if (!runtime) {
1105
+ const module = getLoggingModule();
1106
+ if (!module) {
2842
1107
  fallbackLog("trace", message, fields);
2843
1108
  return;
2844
1109
  }
2845
1110
  try {
2846
- runtime.logTrace(message, toFfiFields(fields));
1111
+ module.logTrace(message, toFfiFields(fields));
2847
1112
  } catch {
2848
1113
  fallbackLog("trace", message, fields);
2849
1114
  }
@@ -2862,6 +1127,22 @@ function createLogger(defaultFields) {
2862
1127
  };
2863
1128
  }
2864
1129
 
1130
+ // src/types/error-type.ts
1131
+ var ErrorType = /* @__PURE__ */ ((ErrorType2) => {
1132
+ ErrorType2["PERMANENT_ERROR"] = "permanent_error";
1133
+ ErrorType2["RETRYABLE_ERROR"] = "retryable_error";
1134
+ ErrorType2["VALIDATION_ERROR"] = "validation_error";
1135
+ ErrorType2["TIMEOUT"] = "timeout";
1136
+ ErrorType2["HANDLER_ERROR"] = "handler_error";
1137
+ return ErrorType2;
1138
+ })(ErrorType || {});
1139
+ function isStandardErrorType(errorType) {
1140
+ return Object.values(ErrorType).includes(errorType);
1141
+ }
1142
+ function isTypicallyRetryable(errorType) {
1143
+ return ["retryable_error" /* RETRYABLE_ERROR */, "timeout" /* TIMEOUT */].includes(errorType);
1144
+ }
1145
+
2865
1146
  // src/types/step-context.ts
2866
1147
  var StepContext = class _StepContext {
2867
1148
  /** The original FFI step event */
@@ -2878,9 +1159,9 @@ var StepContext = class _StepContext {
2878
1159
  inputData;
2879
1160
  /** Results from dependent steps */
2880
1161
  dependencyResults;
2881
- /** Handler-specific configuration (from step_definition.handler.initialization) */
1162
+ /** Handler-specific configuration (from stepDefinition.handlerInitialization) */
2882
1163
  stepConfig;
2883
- /** Step-specific inputs (from workflow_step.inputs, used for batch cursor config) */
1164
+ /** Step-specific inputs (from workflowStep.inputs, used for batch cursor config) */
2884
1165
  stepInputs;
2885
1166
  /** Current retry attempt number */
2886
1167
  retryCount;
@@ -2902,16 +1183,15 @@ var StepContext = class _StepContext {
2902
1183
  /**
2903
1184
  * Create a StepContext from an FFI event.
2904
1185
  *
2905
- * Extracts input data, dependency results, and configuration from
2906
- * the task_sequence_step payload.
1186
+ * TAS-290: All field access uses camelCase (napi-rs auto-converts).
2907
1187
  *
2908
1188
  * The FFI data structure mirrors the Ruby TaskSequenceStepWrapper:
2909
1189
  * - task.context -> inputData (task context with user inputs)
2910
- * - dependency_results -> results from parent steps
2911
- * - step_definition.handler.initialization -> stepConfig
2912
- * - workflow_step.attempts -> retryCount
2913
- * - workflow_step.max_attempts -> maxRetries
2914
- * - workflow_step.inputs -> stepInputs
1190
+ * - dependencyResults -> results from parent steps
1191
+ * - stepDefinition.handlerInitialization -> stepConfig
1192
+ * - workflowStep.attempts -> retryCount
1193
+ * - workflowStep.maxAttempts -> maxRetries
1194
+ * - workflowStep.inputs -> stepInputs
2915
1195
  *
2916
1196
  * @param event - The FFI step event
2917
1197
  * @param handlerName - Name of the handler to execute
@@ -2920,19 +1200,18 @@ var StepContext = class _StepContext {
2920
1200
  static fromFfiEvent(event, handlerName) {
2921
1201
  const task = event.task ?? {};
2922
1202
  const inputData = task.context ?? {};
2923
- const dependencyResults = event.dependency_results ?? {};
2924
- const stepDefinition = event.step_definition ?? {};
2925
- const handlerConfig = stepDefinition.handler ?? {};
2926
- const stepConfig = handlerConfig.initialization ?? {};
2927
- const workflowStep = event.workflow_step ?? {};
1203
+ const dependencyResults = event.dependencyResults ?? {};
1204
+ const stepDefinition = event.stepDefinition ?? {};
1205
+ const stepConfig = stepDefinition.handlerInitialization ?? {};
1206
+ const workflowStep = event.workflowStep ?? {};
2928
1207
  const retryCount = workflowStep.attempts ?? 0;
2929
- const maxRetries = workflowStep.max_attempts ?? 3;
1208
+ const maxRetries = workflowStep.maxAttempts ?? 3;
2930
1209
  const stepInputs = workflowStep.inputs ?? {};
2931
1210
  return new _StepContext({
2932
1211
  event,
2933
- taskUuid: event.task_uuid,
2934
- stepUuid: event.step_uuid,
2935
- correlationId: event.correlation_id,
1212
+ taskUuid: event.taskUuid,
1213
+ stepUuid: event.stepUuid,
1214
+ correlationId: event.correlationId,
2936
1215
  handlerName,
2937
1216
  inputData,
2938
1217
  dependencyResults,
@@ -3043,12 +1322,12 @@ var StepContext = class _StepContext {
3043
1322
  * const value = context.getDependencyField('step_1', 'data', 'items');
3044
1323
  * ```
3045
1324
  */
3046
- getDependencyField(stepName, ...path2) {
1325
+ getDependencyField(stepName, ...path) {
3047
1326
  let result = this.getDependencyResult(stepName);
3048
1327
  if (result === null || result === void 0) {
3049
1328
  return null;
3050
1329
  }
3051
- for (const key of path2) {
1330
+ for (const key of path) {
3052
1331
  if (typeof result !== "object" || result === null) {
3053
1332
  return null;
3054
1333
  }
@@ -3062,10 +1341,14 @@ var StepContext = class _StepContext {
3062
1341
  /**
3063
1342
  * Get the raw checkpoint data from the workflow step.
3064
1343
  *
1344
+ * Note: Checkpoint data from the database uses snake_case keys
1345
+ * (cursor, items_processed, accumulated_results) because it's stored
1346
+ * as a serde_json::Value that passes through napi-rs as-is.
1347
+ *
3065
1348
  * @returns The checkpoint data object or null if not set
3066
1349
  */
3067
1350
  get checkpoint() {
3068
- const workflowStep = this.event.workflow_step ?? {};
1351
+ const workflowStep = this.event.workflowStep ?? {};
3069
1352
  return workflowStep.checkpoint ?? null;
3070
1353
  }
3071
1354
  /**
@@ -3165,6 +1448,130 @@ var StepContext = class _StepContext {
3165
1448
  }
3166
1449
  };
3167
1450
 
1451
+ // src/types/step-handler-result.ts
1452
+ var StepHandlerResult = class _StepHandlerResult {
1453
+ /** Whether the handler executed successfully */
1454
+ success;
1455
+ /** Handler output data (success case) */
1456
+ result;
1457
+ /** Error message (failure case) */
1458
+ errorMessage;
1459
+ /** Error type/category for classification */
1460
+ errorType;
1461
+ /** Optional application-specific error code */
1462
+ errorCode;
1463
+ /** Whether the error is retryable */
1464
+ retryable;
1465
+ /** Additional execution metadata */
1466
+ metadata;
1467
+ /** Orchestration metadata for workflow coordination hints (e.g., backoff, headers) */
1468
+ orchestrationMetadata;
1469
+ constructor(params) {
1470
+ this.success = params.success;
1471
+ this.result = params.result ?? null;
1472
+ this.errorMessage = params.errorMessage ?? null;
1473
+ this.errorType = params.errorType ?? null;
1474
+ this.errorCode = params.errorCode ?? null;
1475
+ this.retryable = params.retryable ?? true;
1476
+ this.metadata = params.metadata ?? {};
1477
+ this.orchestrationMetadata = params.orchestrationMetadata ?? null;
1478
+ }
1479
+ /**
1480
+ * Create a successful handler result.
1481
+ *
1482
+ * This is the primary factory method for creating success results.
1483
+ * Aligned with Ruby and Python worker APIs.
1484
+ *
1485
+ * @param result - The handler output data
1486
+ * @param metadata - Optional additional metadata
1487
+ * @returns A StepHandlerResult indicating success
1488
+ *
1489
+ * @example
1490
+ * ```typescript
1491
+ * return StepHandlerResult.success(
1492
+ * { processed: 100, skipped: 5 }
1493
+ * );
1494
+ * ```
1495
+ */
1496
+ static success(result, metadata) {
1497
+ return new _StepHandlerResult({
1498
+ success: true,
1499
+ result,
1500
+ metadata: metadata ?? {}
1501
+ });
1502
+ }
1503
+ /**
1504
+ * Create a failure handler result.
1505
+ *
1506
+ * @param message - Human-readable error message
1507
+ * @param errorType - Error type/category for classification. Use ErrorType enum.
1508
+ * @param retryable - Whether the error is retryable (default: true)
1509
+ * @param metadata - Optional additional metadata
1510
+ * @param errorCode - Optional application-specific error code
1511
+ * @returns A StepHandlerResult indicating failure
1512
+ *
1513
+ * @example
1514
+ * ```typescript
1515
+ * return StepHandlerResult.failure(
1516
+ * 'Invalid input format',
1517
+ * ErrorType.VALIDATION_ERROR,
1518
+ * false
1519
+ * );
1520
+ * ```
1521
+ *
1522
+ * @example With error code
1523
+ * ```typescript
1524
+ * return StepHandlerResult.failure(
1525
+ * 'Gateway timeout',
1526
+ * ErrorType.TIMEOUT,
1527
+ * true,
1528
+ * { duration_ms: 30000 },
1529
+ * 'GATEWAY_TIMEOUT'
1530
+ * );
1531
+ * ```
1532
+ */
1533
+ static failure(message, errorType = "handler_error" /* HANDLER_ERROR */, retryable = true, metadata, errorCode) {
1534
+ return new _StepHandlerResult({
1535
+ success: false,
1536
+ errorMessage: message,
1537
+ // ErrorType enum values are already strings, so this works directly
1538
+ errorType,
1539
+ errorCode: errorCode ?? null,
1540
+ retryable,
1541
+ metadata: metadata ?? {}
1542
+ });
1543
+ }
1544
+ /**
1545
+ * Check if this result indicates success.
1546
+ */
1547
+ isSuccess() {
1548
+ return this.success;
1549
+ }
1550
+ /**
1551
+ * Check if this result indicates failure.
1552
+ */
1553
+ isFailure() {
1554
+ return !this.success;
1555
+ }
1556
+ /**
1557
+ * Convert to JSON for serialization.
1558
+ *
1559
+ * Uses snake_case keys to match the Rust FFI contract.
1560
+ */
1561
+ toJSON() {
1562
+ return {
1563
+ success: this.success,
1564
+ result: this.result,
1565
+ error_message: this.errorMessage,
1566
+ error_type: this.errorType,
1567
+ error_code: this.errorCode,
1568
+ retryable: this.retryable,
1569
+ metadata: this.metadata,
1570
+ orchestration_metadata: this.orchestrationMetadata
1571
+ };
1572
+ }
1573
+ };
1574
+
3168
1575
  // src/subscriber/step-execution-subscriber.ts
3169
1576
  var loggerOptions2 = {
3170
1577
  name: "step-subscriber",
@@ -3180,7 +1587,7 @@ var pinoLog = pino(loggerOptions2);
3180
1587
  var StepExecutionSubscriber = class {
3181
1588
  emitter;
3182
1589
  registry;
3183
- runtime;
1590
+ module;
3184
1591
  workerId;
3185
1592
  maxConcurrent;
3186
1593
  handlerTimeoutMs;
@@ -3193,13 +1600,13 @@ var StepExecutionSubscriber = class {
3193
1600
  *
3194
1601
  * @param emitter - The event emitter to subscribe to (required, no fallback)
3195
1602
  * @param registry - The handler registry for resolving step handlers
3196
- * @param runtime - The FFI runtime for submitting results (required, no fallback)
1603
+ * @param module - The napi-rs module for submitting results (required, no fallback)
3197
1604
  * @param config - Optional configuration for execution behavior
3198
1605
  */
3199
- constructor(emitter, registry, runtime, config = {}) {
1606
+ constructor(emitter, registry, module, config = {}) {
3200
1607
  this.emitter = emitter;
3201
1608
  this.registry = registry;
3202
- this.runtime = runtime;
1609
+ this.module = module;
3203
1610
  this.workerId = config.workerId ?? `typescript-worker-${process.pid}`;
3204
1611
  this.maxConcurrent = config.maxConcurrent ?? 10;
3205
1612
  this.handlerTimeoutMs = config.handlerTimeoutMs ?? 3e5;
@@ -3236,8 +1643,8 @@ var StepExecutionSubscriber = class {
3236
1643
  pinoLog.info(
3237
1644
  {
3238
1645
  component: "subscriber",
3239
- eventId: payload.event.event_id,
3240
- stepUuid: payload.event.step_uuid
1646
+ eventId: payload.event.eventId,
1647
+ stepUuid: payload.event.stepUuid
3241
1648
  },
3242
1649
  "Received step event in subscriber callback!"
3243
1650
  );
@@ -3337,7 +1744,7 @@ var StepExecutionSubscriber = class {
3337
1744
  pinoLog.info(
3338
1745
  {
3339
1746
  component: "subscriber",
3340
- eventId: event.event_id,
1747
+ eventId: event.eventId,
3341
1748
  running: this.running,
3342
1749
  activeHandlers: this.activeHandlers,
3343
1750
  maxConcurrent: this.maxConcurrent
@@ -3346,7 +1753,7 @@ var StepExecutionSubscriber = class {
3346
1753
  );
3347
1754
  if (!this.running) {
3348
1755
  pinoLog.warn(
3349
- { component: "subscriber", eventId: event.event_id },
1756
+ { component: "subscriber", eventId: event.eventId },
3350
1757
  "Received event while stopped, ignoring"
3351
1758
  );
3352
1759
  return;
@@ -3363,14 +1770,14 @@ var StepExecutionSubscriber = class {
3363
1770
  return;
3364
1771
  }
3365
1772
  pinoLog.info(
3366
- { component: "subscriber", eventId: event.event_id },
1773
+ { component: "subscriber", eventId: event.eventId },
3367
1774
  "About to call processEvent()"
3368
1775
  );
3369
1776
  this.processEvent(event).catch((error) => {
3370
1777
  pinoLog.error(
3371
1778
  {
3372
1779
  component: "subscriber",
3373
- eventId: event.event_id,
1780
+ eventId: event.eventId,
3374
1781
  error: error instanceof Error ? error.message : String(error),
3375
1782
  stack: error instanceof Error ? error.stack : void 0
3376
1783
  },
@@ -3380,37 +1787,65 @@ var StepExecutionSubscriber = class {
3380
1787
  }
3381
1788
  /**
3382
1789
  * Process a step execution event.
1790
+ *
1791
+ * All paths produce a StepHandlerResult — the handler's result or a
1792
+ * system-level failure. This mirrors Python's pattern where system errors
1793
+ * (handler not found, timeout, uncaught exception) become
1794
+ * StepHandlerResult.failure() with appropriate error_type and retryable.
3383
1795
  */
3384
1796
  async processEvent(event) {
3385
- pinoLog.info({ component: "subscriber", eventId: event.event_id }, "processEvent() starting");
1797
+ pinoLog.info({ component: "subscriber", eventId: event.eventId }, "processEvent() starting");
3386
1798
  this.activeHandlers++;
3387
1799
  const startTime = Date.now();
1800
+ const { handlerResult, handlerName, handlerWasInvoked } = await this.resolveAndExecuteHandler(event);
1801
+ const executionTimeMs = Date.now() - startTime;
1802
+ await this.submitResult(event, handlerResult, executionTimeMs);
1803
+ this.emitCompletionEvents(
1804
+ event,
1805
+ handlerResult,
1806
+ handlerName,
1807
+ executionTimeMs,
1808
+ handlerWasInvoked
1809
+ );
1810
+ this.activeHandlers--;
1811
+ }
1812
+ /**
1813
+ * Resolve handler from registry and execute it, returning a StepHandlerResult.
1814
+ *
1815
+ * System-level failures (no handler name, handler not found, uncaught exception)
1816
+ * are converted to StepHandlerResult.failure() with appropriate error_type and
1817
+ * retryable — the caller always gets a result, never an exception.
1818
+ */
1819
+ async resolveAndExecuteHandler(event) {
1820
+ let handlerName = null;
3388
1821
  try {
3389
- const handlerName = this.extractHandlerName(event);
1822
+ handlerName = this.extractHandlerName(event);
3390
1823
  pinoLog.info(
3391
- { component: "subscriber", eventId: event.event_id, handlerName },
1824
+ { component: "subscriber", eventId: event.eventId, handlerName },
3392
1825
  "Extracted handler name"
3393
1826
  );
3394
1827
  if (!handlerName) {
3395
1828
  pinoLog.error(
3396
- { component: "subscriber", eventId: event.event_id },
1829
+ { component: "subscriber", eventId: event.eventId },
3397
1830
  "No handler name found!"
3398
1831
  );
3399
- await this.submitErrorResult(event, "No handler name found in step definition", startTime);
3400
- return;
1832
+ return {
1833
+ handlerResult: StepHandlerResult.failure(
1834
+ "No handler name found in step definition",
1835
+ "permanent_error" /* PERMANENT_ERROR */,
1836
+ false
1837
+ ),
1838
+ handlerName,
1839
+ handlerWasInvoked: false
1840
+ };
3401
1841
  }
3402
1842
  pinoLog.info(
3403
- {
3404
- component: "subscriber",
3405
- eventId: event.event_id,
3406
- stepUuid: event.step_uuid,
3407
- handlerName
3408
- },
1843
+ { component: "subscriber", eventId: event.eventId, stepUuid: event.stepUuid, handlerName },
3409
1844
  "Processing step event"
3410
1845
  );
3411
1846
  this.emitter.emit(StepEventNames.STEP_EXECUTION_STARTED, {
3412
- eventId: event.event_id,
3413
- stepUuid: event.step_uuid,
1847
+ eventId: event.eventId,
1848
+ stepUuid: event.stepUuid,
3414
1849
  handlerName,
3415
1850
  timestamp: /* @__PURE__ */ new Date()
3416
1851
  });
@@ -3418,68 +1853,84 @@ var StepExecutionSubscriber = class {
3418
1853
  const handler = await this.registry.resolve(handlerName);
3419
1854
  pinoLog.info(
3420
1855
  { component: "subscriber", handlerName, handlerFound: !!handler },
3421
- "Handler resolution result"
3422
- );
3423
- if (!handler) {
3424
- pinoLog.error({ component: "subscriber", handlerName }, "Handler not found in registry!");
3425
- await this.submitErrorResult(event, `Handler not found: ${handlerName}`, startTime);
3426
- return;
3427
- }
3428
- pinoLog.info({ component: "subscriber", handlerName }, "Creating StepContext from FFI event");
3429
- const context = StepContext.fromFfiEvent(event, handlerName);
3430
- pinoLog.info(
3431
- { component: "subscriber", handlerName },
3432
- "StepContext created, executing handler"
3433
- );
3434
- const result = await this.executeWithTimeout(
3435
- () => handler.call(context),
3436
- this.handlerTimeoutMs
3437
- );
3438
- pinoLog.info(
3439
- { component: "subscriber", handlerName, success: result.success },
3440
- "Handler execution completed"
3441
- );
3442
- const executionTimeMs = Date.now() - startTime;
3443
- await this.submitResult(event, result, executionTimeMs);
3444
- if (result.success) {
3445
- this.emitter.emit(StepEventNames.STEP_EXECUTION_COMPLETED, {
3446
- eventId: event.event_id,
3447
- stepUuid: event.step_uuid,
3448
- handlerName,
3449
- executionTimeMs,
3450
- timestamp: /* @__PURE__ */ new Date()
3451
- });
3452
- } else {
3453
- this.emitter.emit(StepEventNames.STEP_EXECUTION_FAILED, {
3454
- eventId: event.event_id,
3455
- stepUuid: event.step_uuid,
1856
+ "Handler resolution result"
1857
+ );
1858
+ if (!handler) {
1859
+ pinoLog.error({ component: "subscriber", handlerName }, "Handler not found in registry!");
1860
+ return {
1861
+ handlerResult: StepHandlerResult.failure(
1862
+ `Handler not found: ${handlerName}`,
1863
+ "handler_not_found",
1864
+ false
1865
+ ),
3456
1866
  handlerName,
3457
- error: result.errorMessage,
3458
- executionTimeMs,
3459
- timestamp: /* @__PURE__ */ new Date()
3460
- });
1867
+ handlerWasInvoked: false
1868
+ };
3461
1869
  }
3462
- this.processedCount++;
1870
+ return await this.invokeHandler(event, handler, handlerName);
3463
1871
  } catch (error) {
3464
- this.errorCount++;
3465
1872
  const errorMessage = error instanceof Error ? error.message : String(error);
1873
+ const errorTypeName = error instanceof Error ? error.constructor.name : "Error";
3466
1874
  logError("Handler execution failed", {
3467
1875
  component: "subscriber",
3468
- event_id: event.event_id,
3469
- step_uuid: event.step_uuid,
1876
+ event_id: event.eventId,
1877
+ step_uuid: event.stepUuid,
3470
1878
  error_message: errorMessage
3471
1879
  });
3472
- await this.submitErrorResult(event, errorMessage, startTime);
3473
- this.emitter.emit(StepEventNames.STEP_EXECUTION_FAILED, {
3474
- eventId: event.event_id,
3475
- stepUuid: event.step_uuid,
3476
- error: errorMessage,
3477
- executionTimeMs: Date.now() - startTime,
3478
- timestamp: /* @__PURE__ */ new Date()
3479
- });
3480
- } finally {
3481
- this.activeHandlers--;
1880
+ return {
1881
+ handlerResult: StepHandlerResult.failure(errorMessage, errorTypeName, true, {
1882
+ traceback: error instanceof Error ? error.stack : void 0
1883
+ }),
1884
+ handlerName,
1885
+ handlerWasInvoked: false
1886
+ };
1887
+ }
1888
+ }
1889
+ /**
1890
+ * Create context and invoke the handler, returning its result.
1891
+ *
1892
+ * handlerWasInvoked is true only if the handler returned (not threw).
1893
+ */
1894
+ async invokeHandler(event, handler, handlerName) {
1895
+ pinoLog.info({ component: "subscriber", handlerName }, "Creating StepContext from FFI event");
1896
+ const context = StepContext.fromFfiEvent(event, handlerName);
1897
+ pinoLog.info(
1898
+ { component: "subscriber", handlerName },
1899
+ "StepContext created, executing handler"
1900
+ );
1901
+ const handlerResult = await this.executeWithTimeout(
1902
+ () => handler.call(context),
1903
+ this.handlerTimeoutMs
1904
+ );
1905
+ pinoLog.info(
1906
+ { component: "subscriber", handlerName, success: handlerResult.success },
1907
+ "Handler execution completed"
1908
+ );
1909
+ return { handlerResult, handlerName, handlerWasInvoked: true };
1910
+ }
1911
+ /**
1912
+ * Update counters and emit observability events after step completion.
1913
+ *
1914
+ * A handler returning failure() is still "processed" — the handler ran and
1915
+ * gave a definitive answer. Only system-level errors (handler not found,
1916
+ * timeout, uncaught exception) count as "errors".
1917
+ */
1918
+ emitCompletionEvents(event, handlerResult, handlerName, executionTimeMs, handlerWasInvoked) {
1919
+ const name = handlerName ?? "unknown";
1920
+ if (handlerResult.success || handlerWasInvoked) {
1921
+ this.processedCount++;
1922
+ } else {
1923
+ this.errorCount++;
3482
1924
  }
1925
+ const eventName = handlerResult.success ? StepEventNames.STEP_EXECUTION_COMPLETED : StepEventNames.STEP_EXECUTION_FAILED;
1926
+ this.emitter.emit(eventName, {
1927
+ eventId: event.eventId,
1928
+ stepUuid: event.stepUuid,
1929
+ handlerName: name,
1930
+ ...handlerResult.success ? {} : { error: handlerResult.errorMessage },
1931
+ executionTimeMs,
1932
+ timestamp: /* @__PURE__ */ new Date()
1933
+ });
3483
1934
  }
3484
1935
  /**
3485
1936
  * Execute a function with a timeout.
@@ -3498,18 +1949,10 @@ var StepExecutionSubscriber = class {
3498
1949
  /**
3499
1950
  * Extract handler name from FFI event.
3500
1951
  *
3501
- * The handler name is in step_definition.handler.callable
1952
+ * TAS-290: With napi-rs, handler callable is flattened to stepDefinition.handlerCallable
3502
1953
  */
3503
1954
  extractHandlerName(event) {
3504
- const stepDefinition = event.step_definition;
3505
- if (!stepDefinition) {
3506
- return null;
3507
- }
3508
- const handler = stepDefinition.handler;
3509
- if (!handler) {
3510
- return null;
3511
- }
3512
- return handler.callable || null;
1955
+ return event.stepDefinition?.handlerCallable || null;
3513
1956
  }
3514
1957
  /**
3515
1958
  * Submit a handler result via FFI.
@@ -3518,23 +1961,13 @@ var StepExecutionSubscriber = class {
3518
1961
  * instead of the normal completion path.
3519
1962
  */
3520
1963
  async submitResult(event, result, executionTimeMs) {
3521
- pinoLog.info(
3522
- { component: "subscriber", eventId: event.event_id, runtimeLoaded: this.runtime.isLoaded },
3523
- "submitResult() called"
3524
- );
3525
- if (!this.runtime.isLoaded) {
3526
- pinoLog.error(
3527
- { component: "subscriber", eventId: event.event_id },
3528
- "Cannot submit result: runtime not loaded!"
3529
- );
3530
- return;
3531
- }
1964
+ pinoLog.info({ component: "subscriber", eventId: event.eventId }, "submitResult() called");
3532
1965
  if (result.metadata?.checkpoint_yield === true) {
3533
1966
  await this.submitCheckpointYield(event, result);
3534
1967
  return;
3535
1968
  }
3536
- const executionResult = this.buildExecutionResult(event, result, executionTimeMs);
3537
- await this.sendCompletionViaFfi(event, executionResult, result.success);
1969
+ const serdeResult = this.buildStepExecutionResult(event, result, executionTimeMs);
1970
+ await this.sendCompletionViaFfi(event, serdeResult, result.success);
3538
1971
  }
3539
1972
  /**
3540
1973
  * TAS-125: Submit a checkpoint yield via FFI.
@@ -3544,165 +1977,139 @@ var StepExecutionSubscriber = class {
3544
1977
  */
3545
1978
  async submitCheckpointYield(event, result) {
3546
1979
  pinoLog.info(
3547
- { component: "subscriber", eventId: event.event_id },
1980
+ { component: "subscriber", eventId: event.eventId },
3548
1981
  "submitCheckpointYield() called - handler yielded checkpoint"
3549
1982
  );
3550
1983
  const resultData = result.result ?? {};
3551
1984
  const checkpointData = {
3552
- step_uuid: event.step_uuid,
1985
+ stepUuid: event.stepUuid,
3553
1986
  cursor: resultData.cursor ?? 0,
3554
- items_processed: resultData.items_processed ?? 0
1987
+ itemsProcessed: resultData.items_processed ?? 0
3555
1988
  };
3556
1989
  const accumulatedResults = resultData.accumulated_results;
3557
1990
  if (accumulatedResults !== void 0) {
3558
- checkpointData.accumulated_results = accumulatedResults;
1991
+ checkpointData.accumulatedResults = accumulatedResults;
3559
1992
  }
3560
1993
  try {
3561
- const success = this.runtime.checkpointYieldStepEvent(event.event_id, checkpointData);
1994
+ const success = this.module.checkpointYieldStepEvent(event.eventId, checkpointData);
3562
1995
  if (success) {
3563
1996
  pinoLog.info(
3564
1997
  {
3565
1998
  component: "subscriber",
3566
- eventId: event.event_id,
1999
+ eventId: event.eventId,
3567
2000
  cursor: checkpointData.cursor,
3568
- itemsProcessed: checkpointData.items_processed
2001
+ itemsProcessed: checkpointData.itemsProcessed
3569
2002
  },
3570
2003
  "Checkpoint yield submitted successfully - step will be re-dispatched"
3571
2004
  );
3572
2005
  this.emitter.emit(StepEventNames.STEP_CHECKPOINT_YIELD_SENT, {
3573
- eventId: event.event_id,
3574
- stepUuid: event.step_uuid,
2006
+ eventId: event.eventId,
2007
+ stepUuid: event.stepUuid,
3575
2008
  cursor: checkpointData.cursor,
3576
- itemsProcessed: checkpointData.items_processed,
2009
+ itemsProcessed: checkpointData.itemsProcessed,
3577
2010
  timestamp: /* @__PURE__ */ new Date()
3578
2011
  });
3579
2012
  logInfo("Checkpoint yield submitted", {
3580
2013
  component: "subscriber",
3581
- event_id: event.event_id,
3582
- step_uuid: event.step_uuid,
2014
+ event_id: event.eventId,
2015
+ step_uuid: event.stepUuid,
3583
2016
  cursor: String(checkpointData.cursor),
3584
- items_processed: String(checkpointData.items_processed)
2017
+ items_processed: String(checkpointData.itemsProcessed)
3585
2018
  });
3586
2019
  } else {
3587
2020
  pinoLog.error(
3588
- { component: "subscriber", eventId: event.event_id },
2021
+ { component: "subscriber", eventId: event.eventId },
3589
2022
  "Checkpoint yield rejected by Rust - event may not be in pending map"
3590
2023
  );
3591
2024
  logError("Checkpoint yield rejected", {
3592
2025
  component: "subscriber",
3593
- event_id: event.event_id,
3594
- step_uuid: event.step_uuid
2026
+ event_id: event.eventId,
2027
+ step_uuid: event.stepUuid
3595
2028
  });
3596
2029
  }
3597
2030
  } catch (error) {
3598
2031
  pinoLog.error(
3599
2032
  {
3600
2033
  component: "subscriber",
3601
- eventId: event.event_id,
2034
+ eventId: event.eventId,
3602
2035
  error: error instanceof Error ? error.message : String(error)
3603
2036
  },
3604
2037
  "Checkpoint yield failed with error"
3605
2038
  );
3606
2039
  logError("Failed to submit checkpoint yield", {
3607
2040
  component: "subscriber",
3608
- event_id: event.event_id,
2041
+ event_id: event.eventId,
3609
2042
  error_message: error instanceof Error ? error.message : String(error)
3610
2043
  });
3611
2044
  }
3612
2045
  }
3613
2046
  /**
3614
- * Submit an error result via FFI (for handler resolution/execution failures).
3615
- */
3616
- async submitErrorResult(event, errorMessage, startTime) {
3617
- if (!this.runtime.isLoaded) {
3618
- logError("Cannot submit error result: runtime not available", {
3619
- component: "subscriber",
3620
- event_id: event.event_id
3621
- });
3622
- return;
3623
- }
3624
- const executionTimeMs = Date.now() - startTime;
3625
- const executionResult = this.buildErrorExecutionResult(event, errorMessage, executionTimeMs);
3626
- const accepted = await this.sendCompletionViaFfi(event, executionResult, false);
3627
- if (accepted) {
3628
- this.errorCount++;
3629
- }
3630
- }
3631
- /**
3632
- * Build a StepExecutionResult from a handler result.
2047
+ * Build a NapiStepExecutionResult from a StepHandlerResult.
2048
+ *
2049
+ * The subscriber's only job here is to WRAP the handler result with
2050
+ * execution metadata (timing, worker_id, step_uuid). All handler decisions
2051
+ * (success, retryable, errorType, errorCode, orchestrationMetadata) are
2052
+ * passed through faithfully — the subscriber does not re-interpret them.
3633
2053
  *
3634
- * IMPORTANT: metadata.retryable must be set for Rust's is_retryable() to work correctly.
2054
+ * This mirrors Python's _submit_result() which calls
2055
+ * StepExecutionResult.success_result() or .failure_result() passing
2056
+ * handler fields straight through.
2057
+ *
2058
+ * napi-rs #[napi(object)] maps Option<T> to `?: T`. With
2059
+ * exactOptionalPropertyTypes, optional props must be OMITTED (not null
2060
+ * or undefined) — hence the conditional spread pattern.
3635
2061
  */
3636
- buildExecutionResult(event, result, executionTimeMs) {
3637
- const executionResult = {
3638
- step_uuid: event.step_uuid,
2062
+ buildStepExecutionResult(event, result, executionTimeMs) {
2063
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2064
+ const metadata = {
2065
+ executionTimeMs,
2066
+ completedAt: now,
2067
+ ...this.workerId != null && { workerId: this.workerId },
2068
+ ...Object.keys(result.metadata).length > 0 && { custom: result.metadata },
2069
+ // Pass through handler's classification — subscriber doesn't interpret these
2070
+ ...result.retryable != null && { retryable: result.retryable },
2071
+ ...result.errorType != null && { errorType: result.errorType },
2072
+ ...result.errorCode != null && { errorCode: result.errorCode }
2073
+ };
2074
+ const napiResult = {
2075
+ stepUuid: event.stepUuid,
3639
2076
  success: result.success,
3640
2077
  result: result.result ?? {},
3641
- metadata: {
3642
- execution_time_ms: executionTimeMs,
3643
- worker_id: this.workerId,
3644
- handler_name: this.extractHandlerName(event) ?? "unknown",
3645
- attempt_number: event.workflow_step?.attempts ?? 1,
3646
- retryable: result.retryable ?? false,
3647
- ...result.metadata
3648
- },
3649
- status: result.success ? "completed" : "failed"
2078
+ status: result.success ? "completed" : "failed",
2079
+ metadata
3650
2080
  };
3651
2081
  if (!result.success) {
3652
- executionResult.error = {
2082
+ napiResult.error = {
3653
2083
  message: result.errorMessage ?? "Unknown error",
3654
- error_type: result.errorType ?? "handler_error",
3655
- retryable: result.retryable,
3656
- status_code: null,
3657
- backtrace: null
2084
+ ...result.errorType != null && { errorType: result.errorType },
2085
+ ...result.retryable != null && { retryable: result.retryable }
3658
2086
  };
3659
2087
  }
3660
- return executionResult;
3661
- }
3662
- /**
3663
- * Build an error StepExecutionResult for handler resolution/execution failures.
3664
- *
3665
- * IMPORTANT: metadata.retryable must be set for Rust's is_retryable() to work correctly.
3666
- */
3667
- buildErrorExecutionResult(event, errorMessage, executionTimeMs) {
3668
- return {
3669
- step_uuid: event.step_uuid,
3670
- success: false,
3671
- result: {},
3672
- metadata: {
3673
- execution_time_ms: executionTimeMs,
3674
- worker_id: this.workerId,
3675
- retryable: true
3676
- },
3677
- status: "error",
3678
- error: {
3679
- message: errorMessage,
3680
- error_type: "handler_error",
3681
- retryable: true,
3682
- status_code: null,
3683
- backtrace: null
3684
- }
3685
- };
2088
+ if (result.orchestrationMetadata != null) {
2089
+ napiResult.orchestrationMetadata = result.orchestrationMetadata;
2090
+ }
2091
+ return napiResult;
3686
2092
  }
3687
2093
  /**
3688
2094
  * Send a completion result to Rust via FFI and handle the response.
3689
2095
  *
3690
2096
  * @returns true if the completion was accepted by Rust, false otherwise
3691
2097
  */
3692
- async sendCompletionViaFfi(event, executionResult, isSuccess) {
2098
+ async sendCompletionViaFfi(event, napiResult, isSuccess) {
3693
2099
  pinoLog.info(
3694
2100
  {
3695
2101
  component: "subscriber",
3696
- eventId: event.event_id,
3697
- stepUuid: event.step_uuid,
3698
- resultJson: JSON.stringify(executionResult)
2102
+ eventId: event.eventId,
2103
+ stepUuid: event.stepUuid,
2104
+ success: napiResult.success,
2105
+ status: napiResult.status
3699
2106
  },
3700
- "About to call runtime.completeStepEvent()"
2107
+ "About to call module.completeStepEvent()"
3701
2108
  );
3702
2109
  try {
3703
- const ffiResult = this.runtime.completeStepEvent(event.event_id, executionResult);
2110
+ const ffiResult = this.module.completeStepEvent(event.eventId, napiResult);
3704
2111
  if (ffiResult) {
3705
- this.handleFfiSuccess(event, executionResult, isSuccess);
2112
+ this.handleFfiSuccess(event, isSuccess);
3706
2113
  return true;
3707
2114
  }
3708
2115
  this.handleFfiRejection(event);
@@ -3715,23 +2122,22 @@ var StepExecutionSubscriber = class {
3715
2122
  /**
3716
2123
  * Handle successful FFI completion submission.
3717
2124
  */
3718
- handleFfiSuccess(event, executionResult, isSuccess) {
2125
+ handleFfiSuccess(event, isSuccess) {
3719
2126
  pinoLog.info(
3720
- { component: "subscriber", eventId: event.event_id, success: isSuccess },
2127
+ { component: "subscriber", eventId: event.eventId, success: isSuccess },
3721
2128
  "completeStepEvent() returned TRUE - completion accepted by Rust"
3722
2129
  );
3723
2130
  this.emitter.emit(StepEventNames.STEP_COMPLETION_SENT, {
3724
- eventId: event.event_id,
3725
- stepUuid: event.step_uuid,
2131
+ eventId: event.eventId,
2132
+ stepUuid: event.stepUuid,
3726
2133
  success: isSuccess,
3727
2134
  timestamp: /* @__PURE__ */ new Date()
3728
2135
  });
3729
2136
  logDebug("Step result submitted", {
3730
2137
  component: "subscriber",
3731
- event_id: event.event_id,
3732
- step_uuid: event.step_uuid,
3733
- success: String(isSuccess),
3734
- execution_time_ms: String(executionResult.metadata.execution_time_ms)
2138
+ event_id: event.eventId,
2139
+ step_uuid: event.stepUuid,
2140
+ success: String(isSuccess)
3735
2141
  });
3736
2142
  }
3737
2143
  /**
@@ -3741,15 +2147,15 @@ var StepExecutionSubscriber = class {
3741
2147
  pinoLog.error(
3742
2148
  {
3743
2149
  component: "subscriber",
3744
- eventId: event.event_id,
3745
- stepUuid: event.step_uuid
2150
+ eventId: event.eventId,
2151
+ stepUuid: event.stepUuid
3746
2152
  },
3747
2153
  "completeStepEvent() returned FALSE - completion REJECTED by Rust! Event may not be in pending map."
3748
2154
  );
3749
2155
  logError("FFI completion rejected", {
3750
2156
  component: "subscriber",
3751
- event_id: event.event_id,
3752
- step_uuid: event.step_uuid
2157
+ event_id: event.eventId,
2158
+ step_uuid: event.stepUuid
3753
2159
  });
3754
2160
  }
3755
2161
  /**
@@ -3759,7 +2165,7 @@ var StepExecutionSubscriber = class {
3759
2165
  pinoLog.error(
3760
2166
  {
3761
2167
  component: "subscriber",
3762
- eventId: event.event_id,
2168
+ eventId: event.eventId,
3763
2169
  error: error instanceof Error ? error.message : String(error),
3764
2170
  stack: error instanceof Error ? error.stack : void 0
3765
2171
  },
@@ -3767,7 +2173,7 @@ var StepExecutionSubscriber = class {
3767
2173
  );
3768
2174
  logError("Failed to submit step result", {
3769
2175
  component: "subscriber",
3770
- event_id: event.event_id,
2176
+ event_id: event.eventId,
3771
2177
  error_message: error instanceof Error ? error.message : String(error)
3772
2178
  });
3773
2179
  }
@@ -3793,17 +2199,17 @@ var EventSystem = class {
3793
2199
  /**
3794
2200
  * Create a new EventSystem.
3795
2201
  *
3796
- * @param runtime - The FFI runtime for polling events and submitting results
2202
+ * @param module - The napi-rs module for polling events and submitting results
3797
2203
  * @param registry - The handler registry for resolving step handlers
3798
2204
  * @param config - Optional configuration for poller and subscriber
3799
2205
  */
3800
- constructor(runtime, registry, config = {}) {
2206
+ constructor(module, registry, config = {}) {
3801
2207
  this.emitter = new TaskerEventEmitter();
3802
- this.poller = new EventPoller(runtime, this.emitter, config.poller);
2208
+ this.poller = new EventPoller(module, this.emitter, config.poller);
3803
2209
  this.subscriber = new StepExecutionSubscriber(
3804
2210
  this.emitter,
3805
2211
  registry,
3806
- runtime,
2212
+ module,
3807
2213
  config.subscriber
3808
2214
  );
3809
2215
  }
@@ -3833,11 +2239,11 @@ var EventSystem = class {
3833
2239
  {
3834
2240
  component: "event-system",
3835
2241
  debugListener: true,
3836
- eventId: payload.event?.event_id,
3837
- stepUuid: payload.event?.step_uuid,
2242
+ eventId: payload.event?.eventId,
2243
+ stepUuid: payload.event?.stepUuid,
3838
2244
  eventName: StepEventNames.STEP_EXECUTION_RECEIVED
3839
2245
  },
3840
- `\u{1F50D} DEBUG LISTENER: Received ${StepEventNames.STEP_EXECUTION_RECEIVED} event!`
2246
+ `DEBUG LISTENER: Received ${StepEventNames.STEP_EXECUTION_RECEIVED} event!`
3841
2247
  );
3842
2248
  }
3843
2249
  );
@@ -3916,260 +2322,125 @@ var EventSystem = class {
3916
2322
  };
3917
2323
  }
3918
2324
  };
3919
-
3920
- // src/ffi/index.ts
3921
- init_deno_runtime();
3922
-
3923
- // src/ffi/runtime.ts
3924
- var cachedRuntimeType = null;
3925
- function detectRuntime() {
3926
- if (cachedRuntimeType !== null) {
3927
- return cachedRuntimeType;
3928
- }
3929
- if (typeof globalThis !== "undefined" && "Bun" in globalThis) {
3930
- cachedRuntimeType = "bun";
3931
- return "bun";
3932
- }
3933
- if (typeof globalThis !== "undefined" && "Deno" in globalThis) {
3934
- cachedRuntimeType = "deno";
3935
- return "deno";
3936
- }
3937
- if (typeof process !== "undefined" && process.versions && process.versions.node) {
3938
- cachedRuntimeType = "node";
3939
- return "node";
3940
- }
3941
- cachedRuntimeType = "unknown";
3942
- return "unknown";
3943
- }
3944
- function isBun() {
3945
- return detectRuntime() === "bun";
3946
- }
3947
- function isNode() {
3948
- return detectRuntime() === "node";
3949
- }
3950
- function isDeno() {
3951
- return detectRuntime() === "deno";
3952
- }
3953
- function getRuntimeInfo() {
3954
- const type = detectRuntime();
3955
- switch (type) {
3956
- case "bun": {
3957
- const Bun = globalThis.Bun;
3958
- return {
3959
- type: "bun",
3960
- version: Bun?.version ?? "unknown",
3961
- platform: process?.platform ?? "unknown",
3962
- arch: process?.arch ?? "unknown"
3963
- };
3964
- }
3965
- case "deno": {
3966
- const Deno2 = globalThis.Deno;
3967
- return {
3968
- type: "deno",
3969
- version: Deno2?.version?.deno ?? "unknown",
3970
- platform: Deno2?.build?.os ?? "unknown",
3971
- arch: Deno2?.build?.arch ?? "unknown"
3972
- };
3973
- }
3974
- case "node":
3975
- return {
3976
- type: "node",
3977
- version: process.versions.node,
3978
- platform: process.platform,
3979
- arch: process.arch
3980
- };
3981
- default:
3982
- return {
3983
- type: "unknown",
3984
- version: "unknown",
3985
- platform: "unknown",
3986
- arch: "unknown"
3987
- };
3988
- }
3989
- }
3990
- function getLibraryFilename() {
3991
- const platform = process?.platform ?? "unknown";
3992
- switch (platform) {
3993
- case "darwin":
3994
- return "libtasker_ts.dylib";
3995
- case "linux":
3996
- return "libtasker_ts.so";
3997
- case "win32":
3998
- return "tasker_ts.dll";
3999
- default:
4000
- throw new Error(`Unsupported platform: ${platform}`);
4001
- }
4002
- }
4003
- function getLibraryPath(basePath) {
4004
- const envPath = process.env.TASKER_FFI_LIBRARY_PATH;
4005
- if (envPath) {
4006
- return envPath;
4007
- }
4008
- if (basePath) {
4009
- return `${basePath}/${getLibraryFilename()}`;
4010
- }
4011
- throw new Error(
4012
- "FFI library path not configured. Set TASKER_FFI_LIBRARY_PATH environment variable.\nExample: export TASKER_FFI_LIBRARY_PATH=/path/to/target/debug/libtasker_ts.dylib"
4013
- );
4014
- }
4015
-
4016
- // src/ffi/ffi-layer.ts
4017
2325
  var FfiLayer = class _FfiLayer {
4018
- runtime = null;
4019
- libraryPath = null;
4020
- runtimeType;
4021
- configuredLibraryPath;
4022
- /**
4023
- * Create a new FfiLayer.
4024
- *
4025
- * @param config - Optional configuration for runtime type and library path
4026
- */
2326
+ module = null;
2327
+ modulePath = null;
2328
+ configuredModulePath;
4027
2329
  constructor(config = {}) {
4028
- this.runtimeType = config.runtimeType ?? detectRuntime();
4029
- this.configuredLibraryPath = config.libraryPath;
2330
+ this.configuredModulePath = config.modulePath;
4030
2331
  }
4031
2332
  /**
4032
- * Load the FFI library.
4033
- *
4034
- * Discovers and loads the native library for the current runtime.
2333
+ * Load the napi-rs native module.
4035
2334
  *
4036
- * @param customPath - Optional override for library path (takes precedence over config)
4037
- * @throws Error if library not found or failed to load
2335
+ * @param customPath - Optional override for module path
2336
+ * @throws Error if module not found or failed to load
4038
2337
  */
4039
2338
  async load(customPath) {
4040
- if (this.runtime?.isLoaded) {
2339
+ if (this.module) {
4041
2340
  return;
4042
2341
  }
4043
- const path2 = customPath ?? this.configuredLibraryPath ?? this.discoverLibraryPath();
4044
- if (!path2) {
2342
+ const path = customPath ?? this.configuredModulePath ?? this.discoverModulePath();
2343
+ if (!path) {
4045
2344
  throw new Error(
4046
- `FFI library not found. No bundled native library matches this platform, and TASKER_FFI_LIBRARY_PATH is not set.
2345
+ `napi-rs native module not found. No bundled .node file matches this platform, and TASKER_FFI_MODULE_PATH is not set.
4047
2346
  Current platform: ${process.platform}-${process.arch}
4048
- Supported: linux-x64, linux-arm64, darwin-arm64
4049
- Override: export TASKER_FFI_LIBRARY_PATH=/path/to/libtasker_ts.dylib`
2347
+ Supported: linux-x64, darwin-arm64
2348
+ Override: export TASKER_FFI_MODULE_PATH=/path/to/tasker_ts.linux-x64-gnu.node`
4050
2349
  );
4051
2350
  }
4052
- this.runtime = await this.createRuntime();
4053
- await this.runtime.load(path2);
4054
- this.libraryPath = path2;
2351
+ const nativeModule = __require(path);
2352
+ this.module = nativeModule;
2353
+ this.modulePath = path;
4055
2354
  }
4056
2355
  /**
4057
- * Unload the FFI library and release resources.
4058
- *
4059
- * Safe to call even if not loaded.
2356
+ * Unload the native module and release resources.
4060
2357
  */
4061
2358
  async unload() {
4062
- if (this.runtime?.isLoaded) {
4063
- this.runtime.unload();
4064
- }
4065
- this.runtime = null;
4066
- this.libraryPath = null;
2359
+ this.module = null;
2360
+ this.modulePath = null;
4067
2361
  }
4068
2362
  /**
4069
- * Check if the FFI library is loaded.
2363
+ * Check if the native module is loaded.
4070
2364
  */
4071
2365
  isLoaded() {
4072
- return this.runtime?.isLoaded ?? false;
2366
+ return this.module !== null;
4073
2367
  }
4074
2368
  /**
4075
- * Get the loaded runtime.
2369
+ * Get the loaded napi-rs module.
4076
2370
  *
4077
- * @throws Error if runtime is not loaded
2371
+ * @throws Error if module is not loaded
4078
2372
  */
4079
- getRuntime() {
4080
- if (!this.runtime?.isLoaded) {
2373
+ getModule() {
2374
+ if (!this.module) {
4081
2375
  throw new Error("FFI not loaded. Call load() first.");
4082
2376
  }
4083
- return this.runtime;
2377
+ return this.module;
4084
2378
  }
4085
2379
  /**
4086
- * Get the path to the loaded library.
2380
+ * Backward-compatible alias for getModule().
2381
+ *
2382
+ * @deprecated Use getModule() instead
4087
2383
  */
4088
- getLibraryPath() {
4089
- return this.libraryPath;
2384
+ getRuntime() {
2385
+ return this.getModule();
4090
2386
  }
4091
2387
  /**
4092
- * Get the detected runtime type.
2388
+ * Get the path to the loaded module.
4093
2389
  */
4094
- getRuntimeType() {
4095
- return this.runtimeType;
2390
+ getModulePath() {
2391
+ return this.modulePath;
4096
2392
  }
4097
2393
  /**
4098
- * Find the FFI library path.
4099
- *
4100
- * Static method for finding the library path without creating an instance.
4101
- * Useful for test utilities and pre-flight checks.
2394
+ * Find the napi-rs module path.
4102
2395
  *
4103
2396
  * Resolution order:
4104
- * 1. TASKER_FFI_LIBRARY_PATH environment variable (explicit override)
4105
- * 2. Bundled native library in the package's native/ directory
4106
- *
4107
- * @param _callerDir Deprecated parameter, kept for API compatibility
4108
- * @returns Path to the library if found and exists, null otherwise
2397
+ * 1. TASKER_FFI_MODULE_PATH environment variable (explicit override, for unusual setups)
2398
+ * 2. Bundled .node file in package directory (standard path — `napi build --platform` places it here)
4109
2399
  */
4110
- static findLibraryPath(_callerDir) {
4111
- const envPath = process.env.TASKER_FFI_LIBRARY_PATH;
2400
+ static findModulePath() {
2401
+ const envPath = process.env.TASKER_FFI_MODULE_PATH;
4112
2402
  if (envPath) {
4113
2403
  if (!existsSync(envPath)) {
4114
- console.warn(`TASKER_FFI_LIBRARY_PATH is set to "${envPath}" but the file does not exist`);
2404
+ console.warn(`TASKER_FFI_MODULE_PATH is set to "${envPath}" but the file does not exist`);
4115
2405
  return null;
4116
2406
  }
4117
2407
  return envPath;
4118
2408
  }
4119
- const bundledPath = findBundledNativeLibrary();
2409
+ const bundledPath = findBundledNodeModule();
4120
2410
  if (bundledPath && existsSync(bundledPath)) {
4121
2411
  return bundledPath;
4122
2412
  }
4123
2413
  return null;
4124
2414
  }
4125
2415
  /**
4126
- * Discover the FFI library path.
2416
+ * Backward-compatible alias for findModulePath().
4127
2417
  *
4128
- * Instance method that delegates to the static findLibraryPath.
2418
+ * @deprecated Use findModulePath() instead
4129
2419
  */
4130
- discoverLibraryPath() {
4131
- return _FfiLayer.findLibraryPath();
2420
+ static findLibraryPath(_callerDir) {
2421
+ return _FfiLayer.findModulePath();
4132
2422
  }
4133
- /**
4134
- * Create a runtime adapter for the configured runtime type.
4135
- *
4136
- * NOTE: We use koffi (NodeRuntime) for both Node.js and Bun.
4137
- * koffi is stable and works with both runtimes via Node-API.
4138
- * See: https://bun.sh/docs/runtime/node-api
4139
- */
4140
- async createRuntime() {
4141
- switch (this.runtimeType) {
4142
- case "bun":
4143
- case "node": {
4144
- const { NodeRuntime: NodeRuntime2 } = await Promise.resolve().then(() => (init_node_runtime(), node_runtime_exports));
4145
- return new NodeRuntime2();
4146
- }
4147
- case "deno": {
4148
- const { DenoRuntime: DenoRuntime2 } = await Promise.resolve().then(() => (init_deno_runtime(), deno_runtime_exports));
4149
- return new DenoRuntime2();
4150
- }
4151
- default:
4152
- throw new Error(
4153
- `Unsupported runtime: ${this.runtimeType}. Tasker TypeScript worker requires Bun, Node.js, or Deno.`
4154
- );
4155
- }
2423
+ discoverModulePath() {
2424
+ return _FfiLayer.findModulePath();
4156
2425
  }
4157
2426
  };
4158
- var BUNDLED_LIBRARIES = {
4159
- "linux-x64": "libtasker_ts-linux-x64.so",
4160
- "linux-arm64": "libtasker_ts-linux-arm64.so",
4161
- "darwin-arm64": "libtasker_ts-darwin-arm64.dylib"
2427
+ var BUNDLED_NODE_MODULES = {
2428
+ "linux-x64": "tasker_ts.linux-x64-gnu.node",
2429
+ "darwin-arm64": "tasker_ts.darwin-arm64.node",
2430
+ "darwin-x64": "tasker_ts.darwin-x64.node"
4162
2431
  };
4163
- function findBundledNativeLibrary() {
2432
+ function findBundledNodeModule() {
4164
2433
  const key = `${process.platform}-${process.arch}`;
4165
- const filename2 = BUNDLED_LIBRARIES[key];
4166
- if (!filename2) {
2434
+ const filename = BUNDLED_NODE_MODULES[key];
2435
+ if (!filename) {
4167
2436
  return null;
4168
2437
  }
4169
2438
  let dir = dirname(fileURLToPath(import.meta.url));
4170
2439
  for (let i = 0; i < 5; i++) {
4171
- const candidate = join(dir, "native", filename2);
2440
+ const candidate = join(dir, filename);
4172
2441
  if (existsSync(candidate)) return candidate;
2442
+ const nativeCandidate = join(dir, "native", filename);
2443
+ if (existsSync(nativeCandidate)) return nativeCandidate;
4173
2444
  const parent = dirname(dir);
4174
2445
  if (parent === dir) break;
4175
2446
  dir = parent;
@@ -4177,146 +2448,6 @@ function findBundledNativeLibrary() {
4177
2448
  return null;
4178
2449
  }
4179
2450
 
4180
- // src/ffi/index.ts
4181
- init_node_runtime();
4182
- init_runtime_interface();
4183
-
4184
- // src/types/error-type.ts
4185
- var ErrorType = /* @__PURE__ */ ((ErrorType2) => {
4186
- ErrorType2["PERMANENT_ERROR"] = "permanent_error";
4187
- ErrorType2["RETRYABLE_ERROR"] = "retryable_error";
4188
- ErrorType2["VALIDATION_ERROR"] = "validation_error";
4189
- ErrorType2["TIMEOUT"] = "timeout";
4190
- ErrorType2["HANDLER_ERROR"] = "handler_error";
4191
- return ErrorType2;
4192
- })(ErrorType || {});
4193
- function isStandardErrorType(errorType) {
4194
- return Object.values(ErrorType).includes(errorType);
4195
- }
4196
- function isTypicallyRetryable(errorType) {
4197
- return ["retryable_error" /* RETRYABLE_ERROR */, "timeout" /* TIMEOUT */].includes(errorType);
4198
- }
4199
-
4200
- // src/types/step-handler-result.ts
4201
- var StepHandlerResult = class _StepHandlerResult {
4202
- /** Whether the handler executed successfully */
4203
- success;
4204
- /** Handler output data (success case) */
4205
- result;
4206
- /** Error message (failure case) */
4207
- errorMessage;
4208
- /** Error type/category for classification */
4209
- errorType;
4210
- /** Optional application-specific error code */
4211
- errorCode;
4212
- /** Whether the error is retryable */
4213
- retryable;
4214
- /** Additional execution metadata */
4215
- metadata;
4216
- constructor(params) {
4217
- this.success = params.success;
4218
- this.result = params.result ?? null;
4219
- this.errorMessage = params.errorMessage ?? null;
4220
- this.errorType = params.errorType ?? null;
4221
- this.errorCode = params.errorCode ?? null;
4222
- this.retryable = params.retryable ?? true;
4223
- this.metadata = params.metadata ?? {};
4224
- }
4225
- /**
4226
- * Create a successful handler result.
4227
- *
4228
- * This is the primary factory method for creating success results.
4229
- * Aligned with Ruby and Python worker APIs.
4230
- *
4231
- * @param result - The handler output data
4232
- * @param metadata - Optional additional metadata
4233
- * @returns A StepHandlerResult indicating success
4234
- *
4235
- * @example
4236
- * ```typescript
4237
- * return StepHandlerResult.success(
4238
- * { processed: 100, skipped: 5 }
4239
- * );
4240
- * ```
4241
- */
4242
- static success(result, metadata) {
4243
- return new _StepHandlerResult({
4244
- success: true,
4245
- result,
4246
- metadata: metadata ?? {}
4247
- });
4248
- }
4249
- /**
4250
- * Create a failure handler result.
4251
- *
4252
- * @param message - Human-readable error message
4253
- * @param errorType - Error type/category for classification. Use ErrorType enum.
4254
- * @param retryable - Whether the error is retryable (default: true)
4255
- * @param metadata - Optional additional metadata
4256
- * @param errorCode - Optional application-specific error code
4257
- * @returns A StepHandlerResult indicating failure
4258
- *
4259
- * @example
4260
- * ```typescript
4261
- * return StepHandlerResult.failure(
4262
- * 'Invalid input format',
4263
- * ErrorType.VALIDATION_ERROR,
4264
- * false
4265
- * );
4266
- * ```
4267
- *
4268
- * @example With error code
4269
- * ```typescript
4270
- * return StepHandlerResult.failure(
4271
- * 'Gateway timeout',
4272
- * ErrorType.TIMEOUT,
4273
- * true,
4274
- * { duration_ms: 30000 },
4275
- * 'GATEWAY_TIMEOUT'
4276
- * );
4277
- * ```
4278
- */
4279
- static failure(message, errorType = "handler_error" /* HANDLER_ERROR */, retryable = true, metadata, errorCode) {
4280
- return new _StepHandlerResult({
4281
- success: false,
4282
- errorMessage: message,
4283
- // ErrorType enum values are already strings, so this works directly
4284
- errorType,
4285
- errorCode: errorCode ?? null,
4286
- retryable,
4287
- metadata: metadata ?? {}
4288
- });
4289
- }
4290
- /**
4291
- * Check if this result indicates success.
4292
- */
4293
- isSuccess() {
4294
- return this.success;
4295
- }
4296
- /**
4297
- * Check if this result indicates failure.
4298
- */
4299
- isFailure() {
4300
- return !this.success;
4301
- }
4302
- /**
4303
- * Convert to JSON for serialization.
4304
- *
4305
- * Uses snake_case keys to match the Rust FFI contract.
4306
- */
4307
- toJSON() {
4308
- return {
4309
- success: this.success,
4310
- result: this.result,
4311
- error_message: this.errorMessage,
4312
- error_type: this.errorType,
4313
- error_code: this.errorCode,
4314
- retryable: this.retryable,
4315
- metadata: this.metadata
4316
- };
4317
- }
4318
- };
4319
-
4320
2451
  // src/handler/base.ts
4321
2452
  var StepHandler = class {
4322
2453
  /**
@@ -4531,8 +2662,8 @@ var APIMixin = class {
4531
2662
  /**
4532
2663
  * Make a GET request.
4533
2664
  */
4534
- async get(path2, params, headers) {
4535
- const url = this.buildUrl(path2, params);
2665
+ async get(path, params, headers) {
2666
+ const url = this.buildUrl(path, params);
4536
2667
  return this.fetch(url, {
4537
2668
  method: "GET",
4538
2669
  headers: this.mergeHeaders(headers)
@@ -4541,8 +2672,8 @@ var APIMixin = class {
4541
2672
  /**
4542
2673
  * Make a POST request.
4543
2674
  */
4544
- async post(path2, options) {
4545
- const url = this.buildUrl(path2);
2675
+ async post(path, options) {
2676
+ const url = this.buildUrl(path);
4546
2677
  const body = this.prepareBody(options?.body, options?.json !== false);
4547
2678
  return this.fetch(url, {
4548
2679
  method: "POST",
@@ -4553,8 +2684,8 @@ var APIMixin = class {
4553
2684
  /**
4554
2685
  * Make a PUT request.
4555
2686
  */
4556
- async put(path2, options) {
4557
- const url = this.buildUrl(path2);
2687
+ async put(path, options) {
2688
+ const url = this.buildUrl(path);
4558
2689
  const body = this.prepareBody(options?.body, options?.json !== false);
4559
2690
  return this.fetch(url, {
4560
2691
  method: "PUT",
@@ -4565,8 +2696,8 @@ var APIMixin = class {
4565
2696
  /**
4566
2697
  * Make a PATCH request.
4567
2698
  */
4568
- async patch(path2, options) {
4569
- const url = this.buildUrl(path2);
2699
+ async patch(path, options) {
2700
+ const url = this.buildUrl(path);
4570
2701
  const body = this.prepareBody(options?.body, options?.json !== false);
4571
2702
  return this.fetch(url, {
4572
2703
  method: "PATCH",
@@ -4577,8 +2708,8 @@ var APIMixin = class {
4577
2708
  /**
4578
2709
  * Make a DELETE request.
4579
2710
  */
4580
- async delete(path2, headers) {
4581
- const url = this.buildUrl(path2);
2711
+ async delete(path, headers) {
2712
+ const url = this.buildUrl(path);
4582
2713
  return this.fetch(url, {
4583
2714
  method: "DELETE",
4584
2715
  headers: this.mergeHeaders(headers)
@@ -4587,8 +2718,8 @@ var APIMixin = class {
4587
2718
  /**
4588
2719
  * Make an arbitrary HTTP request.
4589
2720
  */
4590
- async request(method, path2, options) {
4591
- const url = this.buildUrl(path2);
2721
+ async request(method, path, options) {
2722
+ const url = this.buildUrl(path);
4592
2723
  return this.fetch(url, {
4593
2724
  ...options,
4594
2725
  method,
@@ -4680,8 +2811,8 @@ var APIMixin = class {
4680
2811
  clearTimeout(timeoutId);
4681
2812
  }
4682
2813
  }
4683
- buildUrl(path2, params) {
4684
- let url = this.baseUrl + path2;
2814
+ buildUrl(path, params) {
2815
+ let url = this.baseUrl + path;
4685
2816
  if (params) {
4686
2817
  const searchParams = new URLSearchParams();
4687
2818
  for (const [key, value] of Object.entries(params)) {
@@ -4853,23 +2984,23 @@ var ApiHandler = class extends StepHandler {
4853
2984
  // =========================================================================
4854
2985
  // HTTP Methods - Delegate to mixin
4855
2986
  // =========================================================================
4856
- get(path2, params, headers) {
4857
- return this.getApiMixin().get(path2, params, headers);
2987
+ get(path, params, headers) {
2988
+ return this.getApiMixin().get(path, params, headers);
4858
2989
  }
4859
- post(path2, options) {
4860
- return this.getApiMixin().post(path2, options);
2990
+ post(path, options) {
2991
+ return this.getApiMixin().post(path, options);
4861
2992
  }
4862
- put(path2, options) {
4863
- return this.getApiMixin().put(path2, options);
2993
+ put(path, options) {
2994
+ return this.getApiMixin().put(path, options);
4864
2995
  }
4865
- patch(path2, options) {
4866
- return this.getApiMixin().patch(path2, options);
2996
+ patch(path, options) {
2997
+ return this.getApiMixin().patch(path, options);
4867
2998
  }
4868
- delete(path2, headers) {
4869
- return this.getApiMixin().delete(path2, headers);
2999
+ delete(path, headers) {
3000
+ return this.getApiMixin().delete(path, headers);
4870
3001
  }
4871
- request(method, path2, options) {
4872
- return this.getApiMixin().request(method, path2, options);
3002
+ request(method, path, options) {
3003
+ return this.getApiMixin().request(method, path, options);
4873
3004
  }
4874
3005
  // =========================================================================
4875
3006
  // Result Helpers - Delegate to mixin
@@ -6572,9 +4703,9 @@ function ffiEventToDomainEvent(ffiEvent) {
6572
4703
  }
6573
4704
  };
6574
4705
  }
6575
- function createFfiPollAdapter(runtime) {
4706
+ function createFfiPollAdapter(module) {
6576
4707
  return () => {
6577
- const ffiEvent = runtime.pollInProcessEvents();
4708
+ const ffiEvent = module.pollInProcessEvents();
6578
4709
  if (ffiEvent === null) {
6579
4710
  return null;
6580
4711
  }
@@ -7281,21 +5412,21 @@ var HandlerSystem = class {
7281
5412
  * @param path - Path to directory containing handlers
7282
5413
  * @returns Number of handlers loaded
7283
5414
  */
7284
- async loadFromPath(path2) {
7285
- if (!existsSync(path2)) {
7286
- log5.warn(`Handler path does not exist: ${path2}`, { operation: "load_from_path" });
5415
+ async loadFromPath(path) {
5416
+ if (!existsSync(path)) {
5417
+ log5.warn(`Handler path does not exist: ${path}`, { operation: "load_from_path" });
7287
5418
  return 0;
7288
5419
  }
7289
- log5.info(`Loading handlers from: ${path2}`, { operation: "load_from_path" });
5420
+ log5.info(`Loading handlers from: ${path}`, { operation: "load_from_path" });
7290
5421
  try {
7291
- const indexResult = await this.tryImportIndexFile(path2);
5422
+ const indexResult = await this.tryImportIndexFile(path);
7292
5423
  if (indexResult.module) {
7293
5424
  return this.registerHandlersFromModule(indexResult.module, indexResult.path);
7294
5425
  }
7295
5426
  log5.debug("No index file found, scanning for handler files...", {
7296
5427
  operation: "load_from_path"
7297
5428
  });
7298
- return this.scanAndImportHandlers(path2);
5429
+ return this.scanAndImportHandlers(path);
7299
5430
  } catch (error) {
7300
5431
  const errorMessage = error instanceof Error ? error.message : String(error);
7301
5432
  log5.error(`Failed to load handlers from path: ${errorMessage}`, {
@@ -7472,8 +5603,8 @@ var HandlerSystem = class {
7472
5603
  ];
7473
5604
  for (const indexPath of indexPaths) {
7474
5605
  if (existsSync(indexPath)) {
7475
- const module2 = await import(`file://${indexPath}`);
7476
- return { module: module2, path: indexPath };
5606
+ const module = await import(`file://${indexPath}`);
5607
+ return { module, path: indexPath };
7477
5608
  }
7478
5609
  }
7479
5610
  return { module: null, path: null };
@@ -7481,12 +5612,12 @@ var HandlerSystem = class {
7481
5612
  /**
7482
5613
  * Register handlers from a module's exports.
7483
5614
  */
7484
- registerHandlersFromModule(module2, importPath) {
5615
+ registerHandlersFromModule(module, importPath) {
7485
5616
  log5.info(`Loaded handler module from: ${importPath}`, { operation: "import_handlers" });
7486
- if (Array.isArray(module2.ALL_EXAMPLE_HANDLERS)) {
7487
- return this.registerFromHandlerArray(module2.ALL_EXAMPLE_HANDLERS);
5617
+ if (Array.isArray(module.ALL_EXAMPLE_HANDLERS)) {
5618
+ return this.registerFromHandlerArray(module.ALL_EXAMPLE_HANDLERS);
7488
5619
  }
7489
- return this.registerFromModuleExports(module2);
5620
+ return this.registerFromModuleExports(module);
7490
5621
  }
7491
5622
  /**
7492
5623
  * Register handlers from ALL_EXAMPLE_HANDLERS array.
@@ -7507,9 +5638,9 @@ var HandlerSystem = class {
7507
5638
  /**
7508
5639
  * Register handlers from module exports.
7509
5640
  */
7510
- registerFromModuleExports(module2) {
5641
+ registerFromModuleExports(module) {
7511
5642
  let count = 0;
7512
- for (const [exportName, exported] of Object.entries(module2)) {
5643
+ for (const [exportName, exported] of Object.entries(module)) {
7513
5644
  if (this.isValidHandlerClass(exported)) {
7514
5645
  this.registry.register(exported.handlerName, exported);
7515
5646
  count++;
@@ -7576,8 +5707,8 @@ var HandlerSystem = class {
7576
5707
  async importHandlerFile(fullPath) {
7577
5708
  let count = 0;
7578
5709
  try {
7579
- const module2 = await import(`file://${fullPath}`);
7580
- for (const [, exported] of Object.entries(module2)) {
5710
+ const module = await import(`file://${fullPath}`);
5711
+ for (const [, exported] of Object.entries(module)) {
7581
5712
  if (this.isValidHandlerClass(exported)) {
7582
5713
  this.registry.register(exported.handlerName, exported);
7583
5714
  count++;
@@ -7786,7 +5917,7 @@ var WorkerServer = class {
7786
5917
  log7.info("WorkerServer started successfully", {
7787
5918
  operation: "start",
7788
5919
  worker_id: this.workerId,
7789
- version: getVersion(this.ffiLayer.getRuntime())
5920
+ version: getVersion(this.ffiLayer.getModule())
7790
5921
  });
7791
5922
  return this;
7792
5923
  } catch (error) {
@@ -7829,14 +5960,14 @@ var WorkerServer = class {
7829
5960
  this.eventSystem = null;
7830
5961
  log7.info(" Event system stopped", { operation: "shutdown" });
7831
5962
  }
7832
- const runtime = this.ffiLayer.isLoaded() ? this.ffiLayer.getRuntime() : void 0;
7833
- if (isWorkerRunning(runtime)) {
5963
+ const module = this.ffiLayer.isLoaded() ? this.ffiLayer.getModule() : void 0;
5964
+ if (isWorkerRunning(module)) {
7834
5965
  log7.info(" Transitioning to graceful shutdown...", {
7835
5966
  operation: "shutdown"
7836
5967
  });
7837
- transitionToGracefulShutdown(runtime);
5968
+ transitionToGracefulShutdown(module);
7838
5969
  log7.info(" Stopping Rust worker...", { operation: "shutdown" });
7839
- stopWorker(runtime);
5970
+ stopWorker(module);
7840
5971
  log7.info(" Rust worker stopped", { operation: "shutdown" });
7841
5972
  }
7842
5973
  log7.info(" Unloading FFI...", { operation: "shutdown" });
@@ -7890,12 +6021,12 @@ var WorkerServer = class {
7890
6021
  };
7891
6022
  }
7892
6023
  try {
7893
- const runtime = this.ffiLayer.isLoaded() ? this.ffiLayer.getRuntime() : void 0;
7894
- const ffiHealthy = healthCheck(runtime);
6024
+ const module = this.ffiLayer.isLoaded() ? this.ffiLayer.getModule() : void 0;
6025
+ const ffiHealthy = healthCheck(module);
7895
6026
  if (!ffiHealthy) {
7896
6027
  return { healthy: false, error: "FFI health check failed" };
7897
6028
  }
7898
- const workerStatus = getWorkerStatus(runtime);
6029
+ const workerStatus = getWorkerStatus(module);
7899
6030
  if (!workerStatus.running) {
7900
6031
  return { healthy: false, error: "Worker not running" };
7901
6032
  }
@@ -7938,10 +6069,10 @@ var WorkerServer = class {
7938
6069
  });
7939
6070
  log7.info("Loading FFI library...", { operation: "initialize" });
7940
6071
  await this.ffiLayer.load(this.config?.libraryPath);
7941
- log7.info(`FFI library loaded: ${this.ffiLayer.getLibraryPath()}`, {
6072
+ log7.info(`FFI library loaded: ${this.ffiLayer.getModulePath()}`, {
7942
6073
  operation: "initialize"
7943
6074
  });
7944
- setLoggingRuntime(this.ffiLayer.getRuntime());
6075
+ setLoggingRuntime(this.ffiLayer.getModule());
7945
6076
  const totalHandlers = this.handlerSystem.handlerCount();
7946
6077
  if (totalHandlers > 0) {
7947
6078
  log7.info(`Handler registry: ${totalHandlers} handlers registered`, {
@@ -7974,8 +6105,8 @@ var WorkerServer = class {
7974
6105
  bootstrapConfig.databaseUrl = databaseUrl;
7975
6106
  }
7976
6107
  log7.info("Bootstrapping Rust worker...", { operation: "bootstrap" });
7977
- const runtime = this.ffiLayer.getRuntime();
7978
- const result = await bootstrapWorker(bootstrapConfig, runtime);
6108
+ const module = this.ffiLayer.getModule();
6109
+ const result = await bootstrapWorker(bootstrapConfig, module);
7979
6110
  if (!result.success) {
7980
6111
  throw new Error(`Bootstrap failed: ${result.message}`);
7981
6112
  }
@@ -7988,7 +6119,7 @@ var WorkerServer = class {
7988
6119
  log7.info("Starting event processing system...", {
7989
6120
  operation: "start_events"
7990
6121
  });
7991
- const runtime = this.ffiLayer.getRuntime();
6122
+ const module = this.ffiLayer.getModule();
7992
6123
  const eventConfig = {
7993
6124
  poller: {
7994
6125
  pollIntervalMs: this.config?.pollIntervalMs ?? 10,
@@ -8007,7 +6138,7 @@ var WorkerServer = class {
8007
6138
  workerId: this.workerId
8008
6139
  };
8009
6140
  }
8010
- this.eventSystem = new EventSystem(runtime, this.handlerSystem.getRegistry(), eventConfig);
6141
+ this.eventSystem = new EventSystem(module, this.handlerSystem.getRegistry(), eventConfig);
8011
6142
  this.eventSystem.start();
8012
6143
  log7.info("Event processing system started", {
8013
6144
  operation: "start_events",
@@ -8023,8 +6154,9 @@ var WorkerServer = class {
8023
6154
  await this.eventSystem.stop();
8024
6155
  this.eventSystem = null;
8025
6156
  }
8026
- if (isWorkerRunning()) {
8027
- stopWorker();
6157
+ const module = this.ffiLayer.isLoaded() ? this.ffiLayer.getModule() : void 0;
6158
+ if (isWorkerRunning(module)) {
6159
+ stopWorker(module);
8028
6160
  }
8029
6161
  await this.ffiLayer.unload();
8030
6162
  } catch {
@@ -8032,6 +6164,6 @@ var WorkerServer = class {
8032
6164
  }
8033
6165
  };
8034
6166
 
8035
- export { APIMixin, ApiHandler, ApiResponse, BasePublisher, BaseSubscriber, BaseTaskerRuntime, BatchableMixin, ClassLookupResolver, DecisionHandler, DecisionMixin, DecisionType, DefaultPublisher, DenoRuntime, DuplicatePublisherError, ErrorType, EventNames, EventPoller, EventSystem, ExplicitMappingResolver, FfiLayer, HandlerRegistry, HandlerSystem, InProcessDomainEventPoller, MethodDispatchError, MethodDispatchWrapper, MetricsEventNames, NoResolverMatchError, NodeRuntime, PollerEventNames, PublisherNotFoundError, PublisherRegistry, PublisherValidationError, RegistryFrozenError, RegistryResolver, ResolutionError, ResolverChain, ResolverNotFoundError, ShutdownController, StepContext, StepEventNames, StepExecutionSubscriber, StepHandler, StepHandlerResult, SubscriberRegistry, TaskerClient, TaskerClientError, TaskerEventEmitter, WorkerEventNames, WorkerServer, aggregateBatchResults, applyAPI, applyBatchable, applyDecision, bootstrapWorker, createBatchWorkerContext, createBatches, createDomainEvent, createEventPoller, createFfiPollAdapter, createLogger, createStepEventContext, detectRuntime, effectiveMethod, ffiEventToDomainEvent, fromCallable, fromDto, getLibraryPath, getRuntimeInfo, getRustVersion, getVersion, getWorkerStatus, hasResolverHint, healthCheck, isBun, isCreateBatches, isDeno, isNoBatches, isNode, isStandardErrorType, isTypicallyRetryable, isWorkerRunning, logDebug, logError, logInfo, logTrace, logWarn, noBatches, normalizeToDefinition, stopWorker, transitionToGracefulShutdown, usesMethodDispatch };
6167
+ export { APIMixin, ApiHandler, ApiResponse, BasePublisher, BaseSubscriber, BatchableMixin, ClassLookupResolver, DecisionHandler, DecisionMixin, DecisionType, DefaultPublisher, DuplicatePublisherError, ErrorType, EventNames, EventPoller, EventSystem, ExplicitMappingResolver, FfiLayer, HandlerRegistry, HandlerSystem, InProcessDomainEventPoller, MethodDispatchError, MethodDispatchWrapper, MetricsEventNames, NoResolverMatchError, PollerEventNames, PublisherNotFoundError, PublisherRegistry, PublisherValidationError, RegistryFrozenError, RegistryResolver, ResolutionError, ResolverChain, ResolverNotFoundError, ShutdownController, StepContext, StepEventNames, StepExecutionSubscriber, StepHandler, StepHandlerResult, SubscriberRegistry, TaskerClient, TaskerClientError, TaskerEventEmitter, WorkerEventNames, WorkerServer, aggregateBatchResults, applyAPI, applyBatchable, applyDecision, bootstrapWorker, createBatchWorkerContext, createBatches, createDomainEvent, createEventPoller, createFfiPollAdapter, createLogger, createStepEventContext, effectiveMethod, ffiEventToDomainEvent, fromCallable, fromDto, getRustVersion, getVersion, getWorkerStatus, hasResolverHint, healthCheck, isCreateBatches, isNoBatches, isStandardErrorType, isTypicallyRetryable, isWorkerRunning, logDebug, logError, logInfo, logTrace, logWarn, noBatches, normalizeToDefinition, stopWorker, transitionToGracefulShutdown, usesMethodDispatch };
8036
6168
  //# sourceMappingURL=index.js.map
8037
6169
  //# sourceMappingURL=index.js.map